0

I have file and it contents name, surname and age.

john doe 20

lionel messi 33

cristiano ronaldo 35

What I want to do is to get specific person by his/her age and updating any information of him/her. In the sample code below, I want to find a person by his/her age change it.

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

int main () {
    char line[30];
    FILE *fp;
    int age;
    if (!(fp = fopen("test.txt", "rb"))) {  /* validate file open for reading */
        perror ("file open failed");
        return;
    }
    char name[20], surname[20];
    
    while (fgets (line, 30, fp)) {
        int off = 0;
        while (sscanf (line, "%s%s%d%n", name, surname, &age, &off) == 3) {
            if(age == 35) {
                fseek(fp,-2, SEEK_CUR);
                printf("%s", name);
                fprintf(fp, "%d", 19);
            }
            strcpy(line, line+off);
        }
    }
    fclose(fp);
    return 0;
}

However, my code does not work as expected. Sometimes it updates the information but sometimes not. In addition, I used this and this links to create this program. Thx in advance for your helpful comments.

yano
  • 4,827
  • 2
  • 23
  • 35
akoluacik
  • 33
  • 5
  • 1
    Use fopen with "rb+" to open for both reading and writing. – stark Sep 29 '21 at 17:11
  • If you're reading the file with fgets(), that indicates it's a line-based file with variable-sized records. Doing random-access reads and writes on such a file is not possible. Applications that use such files generally read the whole file into memory, make changes in memory, the re-write the whole file. – Lee Daniel Crocker Sep 29 '21 at 17:21
  • Note that the `%n` is going to give you information about the `sscanf` which is not directly related to the position in the file. But, more importantly, you've already read the newline with `fgets`, so the `-2` in the seek goes back to the 5, not the 3. (It backs up over the newline and the 5, not the 5 and the 3). – William Pursell Sep 29 '21 at 17:25
  • Ah, I just realized what you're doing with the offset. Ick. You should restructure the loops entirely, but certainly don't use `strcpy` here. Do something like `char buf[30]; char *line = buf; ... line += off;`. Moving data around like you're doing is a tragedy. – William Pursell Sep 29 '21 at 17:48

0 Answers0