Search code examples
cfilestructtext-filesstructure

How to put data in structure into text file using c?


Let's say I have a structure, and it looks like this:

struct profile {
    char firstName[15], lastName[15];
    int age, phoneNo;
};

and I have a code like this

int main()
{
    FILE *fPtr;
    fPtr=fopen("profile.txt", "w");

    printf("\n\nPlease enter your details:");
    struct profile c;
    printf("\n\nEnter your first name: ");
    gets(c.firstName);
    printf("\nEnter your last name: ");
    gets(c.lastName);
    printf("\nEnter your age: ");
    scanf("%d", &c.age);
    printf("Enter your phone number: ");
    scanf("%d", &c.phoneNo);

    fclose(fPtr);

    return 0;
} 

How do I put the data in this structure into a text file in a way that I will be able to search for specific profiles in the future? Also I'm very new to C so I'd really appreciate it if someone could explain to me if this is possible and how.


Solution

  • When printing string to a file it is important to remember that the string terminator '\0' will result in something that cannot be displayed. So you should avoid writing the strings one by one.

    Another possible issue occurs when, using fwrite an integer is written... as an integer, meaning that it is stored using 4 bytes containing the actual value. For example the value 72 will be stored as

    0x48 0x00 0x00 0x00
    

    that will be displayed with letter H followed by three null characters. So you have to display also numbers as string.

    I suggest doing it using fprintf. It works like printf but it writes to a file instead of stdout. In the following example each field is written in a different row, and a double newline ends the current record:

    fprintf (fPtr, "%s\n%s\n%s\n%s\n%d\n%d\n\n",
              firstName, lastName, custID,
              healthHistory, age, phoneNo);
    

    Note: gets is deprecated as it doesn't perform any string length check. So, for example, if you provide a firstName 20 characters long, the exceeding characters will go beyond the size of that field overwriting the following one. Remember that a char array of size N will contain at most a string N-1 characters long (one is required by the string terminator).

    I suggest using fgets instead:

    fgets (c.firstName, 15, stdin);
    

    at most 15 characters will be read, including string terminator (and including the trailing newline that is sent from command line to terminate the input. You will have to remove it in case you don't need it).