Leon Loo
Leon Loo

Reputation: 1

Why can't string literals stored into txt file using fwrite function

typedef struct student
{
    int rno;
    char *name;
} student;

void create(){
    student *s;
    FILE *fp;
    int n, j, i;
    char nam[50];
    printf("Enter number: ");
    scanf("%d", &n);
    s = (student*)calloc(n, sizeof(student));
    fp = fopen("ask.txt", "w");
    for (i=0; i < n; i++){
        printf("Enter rollno: ");
        scanf("%d", &s[i].rno);
        fflush(stdin);
        printf("Enter name: ");
        scanf("%s", nam);
        s[i].name = nam;
        fwrite(&s[i], sizeof(student), 1, fp);
    }
    fclose(fp);
}

The question requires the name to be a string literal. Is it possible to store string literals into a txt file using fwrite? The s[i].name contains the input, but it couldn't be stored in the txt file

Upvotes: 0

Views: 75

Answers (1)

Jo&#235;l Hecht
Jo&#235;l Hecht

Reputation: 1842

Strings can be stored into files using fwrite.

The problem with the code you exposed, concerning this particular question, is that the struct student does not contain a string: it contains a pointer to a string.

It should work better with a struct like this one:

typedef struct student
{
    int rno;
    char name[50];
} student;

Upvotes: 1

Related Questions