简体   繁体   English

C程序不写入文件

[英]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.我正在阅读第 11 章(文件处理)中的“C:如何编程”,并附带了这个算法,将一个字符串附加到名为info.txt的文件中,但它根本不起作用。 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.我猜您错误地插入了 EOF。 As it is answered here , EOF is inserted using CTRL+D in Unix systems and using CTRL+Z in Windows.正如这里回答的那样,在 Unix 系统中使用CTRL+D插入 EOF,在 Windows 中使用CTRL+Z插入。

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.完全使用您的代码对我有用,所以我猜您正在尝试使用CTRL+C或其他命令插入 EOF,这会关闭应用程序并将文件留空。

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]此外,如果您希望它始终附加,即使您关闭程序并再次打开它,您也应该使用模式附加“a”而不是写“w” [参考]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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