问题
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");
}
The compiler throws the following error:
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.
回答1:
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
//...
}
Also 1st argument to fprintf(...) is of type FILE *
. Change:
fprintf(filename, "%10%i", p[i]);
^^^^^^^^
to
fprintf(fp, "%i", p[i]);
^^//pointer to FILE struct
回答2:
You must use the FILE *
that you obtained when you opened the file.
fprintf(fp, "%10%i", p[i]);
The error message states that fprintf
function expects a FILE *
, not a char *
(or, what is the same, a char[]
).
回答3:
Right. All the C compiler sees, when you call fprintf, is a string literal (a char*
) and it is not designed to infer that a string refers to a filename. That's what fopen is for; it gives you a special type of pointer that indicates an open file. Note that your code doesn't actually do anything with fp after it opens the file, except to close it. So you just need to substitute fp
in for filename
in your call to fprintf.
回答4:
Should check the return value of fopen.
Should be:
fprintf(fp, "%10d", p[i]);
Should move fclose out of the outer for loop.
来源:https://stackoverflow.com/questions/19625039/writing-an-array-to-a-file-in-c