在 C 中将数组写入文件 [英] Writing an array to a file in C
本文介绍了在 C 中将数组写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将前 N 个素数的数组写入 txt 文件,每行 5 个条目,每个条目之间有 10 个空格.相关代码如下:
I am attempting to write an array of the first N primes to a txt file in rows of 5 entries each, with 10 spaces between each entry. The relevant code is as follows:
#include<stdio.h>
#include<math.h>
#define N 1000
...
void writePrimesToFile(int p[N], char filename[80])
{
int i;
FILE *fp = fopen(filename, "w");
for(i = 0; i<=N-1; i++)
{
for(i = 0; i<5; i++)
{
fprintf(filename, "%10%i", p[i]);
}
printf("/n");
fclose(fp);
}
printf("Writing array of primes to file.\n");
}
编译器抛出以下错误:
primes.c:40:4: warning: passing argument 1 of ‘fprintf’ from incompatible pointer type [enabled by default]
fprintf(filename, "%10%i", p[i]);
^
In file included from /usr/include/stdio.h:29:0,
from primes.c:1:
/usr/include/stdio.h:169:5: note: expected ‘struct FILE *’ but argument is of type ‘char *’
int _EXFUN(fprintf, (FILE *, const char *, ...)
^
许多谷歌搜索都没有结果.任何帮助将不胜感激.
Numerous Google searches have not been fruitful. Any help would be much appreciated.
推荐答案
在允许使用 fp 之前测试 fopen()
的输出:
Test the output of fopen()
before allowing fp to be used:
FILE *fp = fopen(filename, "w");
if(fp)//will be null if failed to open
{
//continue with stuff
//...
}
fprintf(...) 的第一个参数也是 文件 *
.变化:
Also 1st argument to fprintf(...) is of type FILE *
. Change:
fprintf(filename, "%10%i", p[i]);
^^^^^^^^
到
fprintf(fp, "%i", p[i]);
^^//pointer to FILE struct
这篇关于在 C 中将数组写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文