LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Structures (https://www.linuxquestions.org/questions/programming-9/structures-146179/)

AMMullan 02-14-2004 08:25 PM

Structures
 
Hey all :)

I've been trying to get into structures for a while but can't figure out how to use them to their full potential.

What i'm trying to do is have a file with 3 fields: name, password and comment. I wanna be able to use a structure to view/add these fields.

How easy is this to do? I understand how to get info (i.e. i've been working with the passwd structure alot) but not how to lay everything out....

Oh BTW i'm programming in C :)

Thanks in advance :D

Mohsen 02-14-2004 09:14 PM

It's quite easy!
usign fread/read or fwrite/write you can read a record or store a record in a file.
Code:

structure user{
  char[256] pass;
  char[256] name;
  char[256] comment;
};

int main () {
  // read from the file using fread (or read syscall)
  // write to the file using fwrite (or write syscall)
  FILE* fp = fopen ("myFile.dat", "w")
  struct user u = {
    "12345", "Mohsen", "Salaam!"
  }
  fwrite (u, 3, 255);

  // reading from the file is identical to some extent
  return 0;
}


AMMullan 02-14-2004 09:49 PM

K wow :) I've never run into fwrite so didn't that either (guess it takes longer to learn all the functions you can you than I thought :D

Ummm had to change a few things (some syntax errors) but the fwrite requires 4 arguments, not 3... I had a read of the man page for it and it's meant to be something like this:

Code:

fwrite (u, 255, 3, fp);
But because u is part of a structure it's incompatible....

Also as we gave this structure an alias of u do we call the information like this:

Code:

struct user *foo;
  printf("User: %s\n", foo.u->name);

?

Thanks heaps - u've already shown me quite a bit :D

:study:

AMMullan 02-14-2004 11:51 PM

Also is it possible to dynamically make structures from variables - i.e.

Code:

char name[256];

printf("Enter your name: ");
fgets(name, sizeof(name), stdin);

...

struct user %s {"%s", "%s", "%s"}, name, name, pass, comment;

I know that doesn't work but I wanna see if I can do something like that :confused:

:newbie:

worldmagic 02-18-2004 07:24 AM

Nopes you can not dynamicly create structures.

But you could create "name-value" pairs.

Code:

struct pair {
  char name[16];
  char value[16];
}

struct myData {
  struct pair field1;
  struct pair field2;
}

or why not:

Code:

  struct pair files[2];

worldmagic 02-18-2004 07:25 AM

erh.. files[2] should be fields[2] =)

AMMullan 02-18-2004 11:39 AM

Kewl i'll read up a bit more on the pair type and see how I go... Thanks :D

Also just bought "C by Example" and looks like a really good book, might learn a few things from it :)

Thanks all


All times are GMT -5. The time now is 02:37 AM.