【发布时间】: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); }