c - 在 C 语言中,为什么 (while .. getchar()) 不写入我的文件?

标签 c file argv getchar

我需要编写一个程序,要求用户输入字符串,当用户按“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;
}

关于c - 在 C 语言中,为什么 (while .. getchar()) 不写入我的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66405751/

相关文章:

c - 我怎样才能在 C 中具体取出整数中的数字?

c - 斯坦福 GraphBase .gb 格式

C - 终止的好方法

qt - 在 Qt Creator 构建目录中包含资源文件

c++ - 有没有办法在运行时设置 argv 和 argc 参数?

c - 如何将结构体数组复制到同一数组中的另一个结构体?

c# - 在 C# 中运行仍处于打开状态的 exe 文件

c - 分配 argv[i] = NULL

c++ - 将 argv[ ] 的输入转换为 char?

ruby-on-rails - 如何在 Rails 的目录结构中查找文件