【问题标题】:Writing an array into a text file [closed]将数组写入文本文件[关闭]
【发布时间】:2014-03-22 12:43:26
【问题描述】:

我正在尝试将字符数组写入 txt 文件。我自己找不到错误。这应该很好用,但是这段代码没有将我想要的数组写入 txt 文件。即使我想覆盖一个txt文件,它也只是写空白字符。

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

void main(void){

   char temp[] = "Print newline, word, and byte counts for each FILE, and a total if more than one FILE is specified. With no FILE, or when FILE is a dash (\"-\"), wc operates on standard input. (A word is a non-zero-length sequence of characters delimited by white space.)";

   FILE *fpw = fopen("output.txt","w");
   if(ferror(fpw)) printf("Error");

   fputs(temp,fpw);
   fclose(fpw);

}

【问题讨论】:

  • 只有在代码要编译时才可能写入文件。
  • 嗯,程序运行良好。但是,不会将任何内容写入指定的 txt 文件。
  • close(fpw); ===> fclose(fpw);,并注意您的编译器警告。
  • 我试试这个能用吗?
  • if (ferror(fpw)) 不是检查fopen 是否成功的正确方法。你应该使用类似if (!fpw) { perror("output.txt"); exit(EXIT_FAILURE); }

标签: c arrays file file-io


【解决方案1】:

临时字符串中有 " 字符。用反斜杠将它们转义,如下所示:

char temp[] "String with \"'s in it.";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多