为什么 (while .. getchar()) 在 C 中不写入我的文件?

Why does (while .. getchar()) does not write to my file, in C?

我需要编写一个程序,要求用户输入字符串,每个字符串在用户按下 'Enter' 时结束。

到目前为止,这是我的代码:

 int is_file_exists(char *file_name)
{
    
    FILE *file;
    if ((file = fopen(file_name,"r"))!=NULL)    
        {
            /* file exists */
            fclose(file);
            return 1;
        }    
    else  
        {
            //File not found, no memory leak since 'file' == NULL
            //fclose(file) would cause an error
            return 0;
        }
        
}

int main(int argc, char **argv)
{
    char c;
    FILE *file;

    if (argc >= 2)
    {
         if (is_file_exists(argv[1]))
         {
             file = fopen(argv[1], "w");
         }
         else
         {
             return 0;
         }
    }
    else
    {
         file = fopen("file.txt", "w");
    }

    while ((c = getchar()) != EOF)
    {
        putc(c, file);
    }

    return 0;
}

到目前为止,代码已编译并正在创建文件,但没有向其中写入任何内容。

编辑:我还需要一些函数指针,请参阅我对所选答案的评论

我认为问题之一是您打开和关闭文件,然后又重新打开它。最好只使用指针将其打开,同时测试打开文件是否没有问题。另一个问题是您在文件中写入时,您不喜欢向其附加文本吗?那么这是你的决定。至于代码:

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

typedef struct mystruct {
    char *exit_word;
    void (*exit_fptr)(int); // man exit
    int (*strcmp_fptr)(const char *, const char*); // man strcmp
}              t_mystruct;

int is_file_exists(char *filename, FILE **file)
{
    return (*file = fopen(filename,"a")) > 0;
}

#define BUFF_SIZE 1024

int main(int argc, char **argv)
{
    char c;
    FILE *file;
    t_mystruct s = {.exit_word = "-exit", .exit_fptr = &exit, .strcmp_fptr = &strcmp};

    if (argc >= 2) {
         if (!(is_file_exists(argv[1], &file)))
            return 0;
    }
    else
         file = fopen("file.txt", "a"); // open the file in append mode

    char buffer[BUFF_SIZE];
    while (42) {
        int i = 0;
        memset(buffer, 0, BUFF_SIZE);
        while ((c = getchar()) != '\n')
            buffer[i++] = c;
        if (!s.strcmp_fptr(buffer,s.exit_word)) {// exit if user type exit, allow you to fclose the file
            fclose(file);
            s.exit_fptr(EXIT_SUCCESS); // better to use the define
        }
        buffer[i] = '\n';
        fputs(buffer, file);
    }
    fclose(file);
    return 0;
}

您的代码可以工作

记得输入完后按Ctrl+d。该文件将包含您期望的内容

您的代码等待 EOF 退出循环。 Ctrl+d 是输入 EOF 的一种方式,否则程序永远不会结束。 putc会先写入缓存,再写入磁盘。这是文件系统的一种优化机制。您可以选择在打开文件时通过 DirectIO 避免这种情况。

当程序正常终止时,文件会自动关闭,然后将缓存中的数据复制到磁盘;

但是当程序异常终止时,缓存中的数据可能会丢失。

文件应该关闭

需要fclose。 open 和 close 应该成对组织,就像 malloc 和 free 一样。