0

I try to edit a file in C but it does not work. The code creates the file if it does not exist but it can not edit it. I tried to change the file opening status but nothing. This is the code :

typedef struct{
    char name[MAXSTRING];
    int id;
  }student;


int main(int argc, const char **argv){

        i = 0;
        FILE *fp;
        if ( (fp=fopen("StudentsFile.dat", "w") ) == NULL ){
            printf("FILE CAN NOT OPEN");
        }else{
             printf("INSERT NAME AND ID OF THE STUDENT\n");
            student *stArray = (student *) malloc(sizeof(student));
            scanf("%s" "%d", &stArray->name, &stArray->id);
            while (!feof(stdin))
            {

                fprintf( fp ,"%s", stArray->name );
                scanf("%s" "%d", &stArray->name, &stArray->id);
                printf("%s ", &stArray->name);

            }
            fclose (fp);
         }
             return 0;

     }
  • 1
    How do you know it can't edit it? – Oppen May 20 '20 at 16:14
  • Note `"%s" "%d"` will be merged into `"%s%d"', so the string argument will consume the integer argument. You want it to be `"%s %d"`. EDIT: no, the space in the input should fix that. – Oppen May 20 '20 at 16:16
  • Also, how are you calling the program? If you run it interactively you have to end it with `Ctrl+d` to close `stdin` and let it go out of the loop. If you run interactively and finish with `Ctrl+c` it will quit without calling `fclose`, so it won't flush the buffer and you will not see the writes. – Oppen May 20 '20 at 16:19
  • I copied the code from the university's book and the fclose is out of the loop. That's why I didn't put it in. I followed your instructions and it works. Thank you!!! – Apostolis Dimitriou May 20 '20 at 17:02
  • It's correct for it to be out of the loop, but you need to make sure the code after the loop runs, i.e., not quitting abruptly. – Oppen May 20 '20 at 17:19

1 Answers1

0

This statement seems to be suspected:

scanf("%s" "%d", &stArray->name, &stArray->id);

It should be:

scanf("%s %d", &stArray->name, &stArray->id);

Anyway, it seems like you're trying to append data into StudentsFile.dat. If you use the w mode, it'll just write but won't append. You need to use "a" mode in this situation.

Therefore, you should create another file pointer as shown:

FILE *fp2 = fopen("StudentsFile.dat", "a")

Use fprintf() for fp2 rather than fp1 in this case.

In the while loop, you don't need any scanf() because you're trying to append the data into the file.

Note: You're missing %d for stArray->id in fprintf() statement and don't forget to close fp2 after fp.

Here's the clear method to append text into a file.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34