首页 > 解决方案 > 变量文件可能尚未初始化

问题描述

这是我的功能。我的 charpeca定义为char peca[MAX_BUFFER],其中max_buffer1024。我想在我的“tabuleiro”文件中写入里面的内容peca,但我的程序总是说该文件可能尚未初始化。

所以我的函数不打印我的 txt 文件,有什么想法吗?

void write_txt (char *peca){
    FILE *file;
    fopen("tabuleiro.txt","w");
    fprintf(file,"M: %c\n",*peca);
    fclose(file);
}

标签: cfile

解决方案


所以我的函数没有打印在我的 txt 文件中

将返回指针分配FILE* fopen(const char* filename, const char* mode );给您的文件,如下所示:

file = fopen("tabuleiro.txt", "w");

然后,你会在打开它后检查 if fileis not NULL,以便知道它打开成功。

%s此外,您可能希望使用用于字符串的 写入文件。

所以,你可以试试这个:

void write_txt (char *peca) {
    FILE *file = fopen("tabuleiro.txt", "w");
    if(!file) {
      printf("File did NOT open successfully!\n")
      // error handling here..do not execute the fprintf() or fclose()
    }
    fprintf(file,"M: %s\n",*peca);
    fclose(file);
}

推荐阅读