简体   繁体   中英

Problems reading C txt file

I'm making a C program and I need it to save some integers and strings when the user closes the program. I managed to do it successfully. The txt file is created and everything is in correctly written, the problem is, when I try to read it on the compiler it's not working properly. My code is: To Write:

saveFile = fopen("saveFileP.txt", "w");
  for (int i=0; i<numberofPeople; i++) {
    fputs(people[i].firstName, saveFile);
    fputs(" ", saveFile);
    fputs(people[i].lastName, saveFile);
    fputs(" ", saveFile);
    fprintf(saveFile, "%d ", people[i].cash);
    fprintf(saveFile, "%d ", people[i].position);
    fprintf(saveFile, "%d ", people[i].inGame);
}

To Read:

saveFile = fopen("saveGameP.txt", "r");
for (int i=0; i<numberOfPeople; i++) {
    fgets(people[i].firstName, 20, saveFile);
    fgets(people[i].lastName, 20, saveFile);
    fscanf(saveFile, "%d", &people[i].cash);
    fscanf(saveFile, "%d", &people[i].position);
    fscanf(saveFile, "%d", &people[i].inGame);
}

And then I ask it to print the values onto the screen and it writes wrong values, but on the txt file the values are correct. What am I doing wrong? Thank you.

PS: I am using Xcode.

Try

for (int i=0; i<numberOfPeople; i++) {
    fscanf(saveFile,"%s %s",people[i].firstName,people[i].lastName);

    fscanf(saveFile, "%d", &people[i].cash);
    fscanf(saveFile, "%d", &people[i].position);
    fscanf(saveFile, "%d", &people[i].inGame);
}

I've used fscanf() because fgets() reads a whole line until a \\n character is encountered(or until a maximum of 20 characters is read) and not until it finds a space. Since,both firstName and lastName are seperated by a space,you can use fscanf() .

fgets() reads till newline character and it includes \\n

In this case isn't both firstname and lastname are on the same line seperated by a space?

In your code you are reading the first line and fetching just first 20 chars and the rest is left unread.

Then you are moving to the next line without actually reading the later part.

You can fix this by doing

  1. Read the whole line using fgets()
  2. Use strtok() and break the line to tokens using space as delimiter
  3. Then copy tokens to your arrays

I suggest getline ( though not specified in POSIX), Use that to read a full line ( to verify that use printf to print the line)

Then if your values are separated by spaces, for example. Use strtok function to tokenize the line that you just read.

For example:

strtok("123: A String", " ");  //returns a pointer to the tokenized string
strtok(NULL, " ");
strtok(NULL, " ");
strtok(NULL, " ");

will break the string as: "123:" "A" "String"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM