0

I was reading "C: How to program" on chapter 11 (File handling) and came with this algorithm, to append a string to a file named info.txt but it isn't working at all. What am I doing wrong?

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

int main(void)
{
    FILE *fp = fopen("info.txt","w");
    char buff[100];
    if(fp == NULL){
        fprintf(stdout,"Error opening file\n");
        exit(1);
    }
 

    while(!feof(stdin)){
        fprintf(stdout,"Type a string/\nEOF ends input\n");
        if(!fgets(buff,sizeof buff,stdin)){
            fprintf(stderr,"Error reading string");
            exit(2);
        }
        buff[strcspn(buff,"\n")] = 0;
        fprintf(fp,"%s",buff);
    }
    fclose(fp); 
}
  • 1
    « it isn't working at all » could you describe more precisely? – prog-fh Jul 13 '21 at 23:24
  • 1
    Your problem description isn't very helpful. What exactly happens when you run this program? (Is the problem that it doesn't *append*? Because nothing in the code causes the write operation to occur at the end of the file.) – David Schwartz Jul 13 '21 at 23:24

1 Answers1

1

I guess you are inserting EOF wrongly. As it is answered here, EOF is inserted using CTRL+D in Unix systems and using CTRL+Z in Windows.

Using exactly your code it works for me, so I guess you are trying to insert EOF using CTRL+C, or another command, which closes the application and leaves the file empty.

Also, if you want it to append always, even if you close the program and open it again, you should use the mode append "a" instead of write "w" [reference]

FILE *fp = fopen("info.txt","a");