0

I want to write data in structure to a text file. But it ends up showing strange characters in the text file. I have changed many forms of fwrite arguments but none works. Please someone help me. Sorry for the long code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Student
{
    char name[30];
    int id;
    int score;
    int score2;
    int score3;
};

int main()
{
    printf("Please input the information below into grade.data!\n");
    printf("Ends with name's value equal to 'E'\n");
    struct Student stu[10];
    int i = 0, maxlength = 0; //size of longest name
    printf("Name No Math Chi Eng\n");
    while (true){
        scanf("%s", stu[i].name);
        if(maxlength < strlen(stu[i].name)) maxlength = strlen(stu[i].name);
        if (stu[i].name[0] == 'E') break;
        scanf("%d", &stu[i].id);
        scanf("%d", &stu[i].score1);
        scanf("%d", &stu[i].score2);
        scanf("%d", &stu[i].score3);
        i++;
    }

    FILE* fp;
    fp = fopen("test.txt", "wb");
    if (fp == NULL) {
        printf("Open file error!");
        exit(-1);
    }

    fwrite(&stu, sizeof(struct Student), 1, fp);
    fclose(fp);
    printf("Name%-*c No%-*c Math Chi Eng\n", maxlength-4, ' ', 7, ' ');
    for (int i = 0; stu[i].name[0] != 'E'; i++) {
        printf("%-*s ", maxlength, stu[i].name);
        printf("%-*d ", 9, stu[i].id);
        printf("%-*d ", 4, stu[i].score1);
        printf("%-*d ", 3, stu[i].score2);
        printf("%d\n", stu[i].score3);
    }
    return 0;
}

That is the input and file after fwrite is executed

  • 5
    *I want to write data in **structure** to a **text file*** A structure is not text. `fwrite()` writes the raw byte contents. – Andrew Henle Mar 05 '20 at 14:57
  • 3
    fwrite ==> fprintf – pmg Mar 05 '20 at 15:00
  • @AndrewHenle I have changed w to wb but it still wont work – Susan Tandiono Mar 05 '20 at 15:10
  • It's more idiomatic to iterate over an array of structs with: `for( struct Student *p=stu; p < stu + 10; p++) scanf("%s", p->name); ...` The s[i].m notation gets unwieldy very quickly. `->` is your friend. – William Pursell Mar 05 '20 at 15:20
  • It will write the structure to a file but not in a human readable format. You can use fread to read the data back. On Linux, use od to look at the file, on windows have a look at https://stackoverflow.com/questions/1724586/can-i-hex-edit-a-file-in-visual-studio on how to view a binary file – cup Mar 05 '20 at 15:31
  • Using `scanf()` to read (potentially malformed) user input, without checking return code -> UB waiting to happen. You don't *know* what's in `stu` after your input. You might be looking at uninitialized values. – DevSolar Mar 06 '20 at 08:13

1 Answers1

0

It because members in the structure Student other than name are integers. Convert integer values to ASCII and then store it in the file.

Valerii Boldakov
  • 1,751
  • 9
  • 19
alagesan
  • 1
  • 2