首页 > 解决方案 > 为什么 (while .. getchar()) 不会在 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;
}

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

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

标签: cfileargvgetcharwrite

解决方案


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

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

推荐阅读