简体   繁体   中英

C program not writing to a file

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); 
}

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");

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