Reputation: 33
I have my function dumpArray(); which does this:
void dumpArray(void)
{
while(p <= i)
{
printf("%i:", packet[p].source);
printf("%i:", packet[p].dest);
printf("%i:", packet[p].type);
printf("%i\n", packet[p].port);
p++;
}
}
And I'm trying to pass this into a fprintf(); as such:
void fWrite(void)
{
char fileName[30] = { '\0' };
printf("Please specify a filename: ");
scanf("%s", fileName) ;
FILE *txtFile;
txtFile = fopen(fileName, "w");
if (txtFile == NULL)
{
printf("Can't open file!");
exit(1);
}
else fprintf(txtFile, dumpArray());
}
I'm trying to write the result of dumpArray(); into the file.
Could anyone see where I'm going wrong and point me in the right direction.
Upvotes: 1
Views: 1484
Reputation: 3393
The function declaration of fprintf states that it want some char* argument but dumpArray() is not returning a char*.
int fprintf ( FILE * stream, const char * format, ... );
If you want write to file in the dumpArray(), you can pass txtFile to dumpArray() and do fprintf inside the function. Or you could first collect all data you want to write to the file in a buffer (such as a char[]) and then write it altogether.
For example:
void dumpArray(FILE * txtFile)
{
while(p <= i)
{
fprintf(txtFile, packet[p].source);
fprintf(txtFile, packet[p].dest);
fprintf(txtFile, packet[p].type);
fprintf(txtFile, packet[p].port);
fprintf(txtFile, "\n");
p++;
}
}
void fWrite(void)
{
char fileName[30] = { '\0' };
printf("Please specify a filename: ");
scanf("%s", fileName) ;
FILE *txtFile;
txtFile = fopen(fileName, "w");
if (txtFile == NULL)
{
printf("Can't open file!");
exit(1);
}
else dumpArray(txtFile);
Upvotes: 1
Reputation:
Your first function is dumping its output into stdout
and returning nothing, so it just won't result in an output that fprintf
can capture.
You'll need to figure out how long all of those printf
strings are and allocate the appropriate amount of memory to sprintf
it and then return the string.
Alternatively, you should pass a function pointer to dumpArray
pointing at the printf
-like function that will instead write to a file:
void printfLike(format, data) {
fprintf(fileConst, format, data);
}
...
dumpArray(printfLike);
Something of that nature.
Upvotes: 2
Reputation: 2372
You could rewrite dumparray to either write to stdout or to your textfile depending which stream you pass in.
So you would change all of your printf calls to fprintf and pass the stream as the first argument.
Upvotes: 3
Reputation: 60037
Where do you start?
Plead look up the page for fprintf
and printf
.
Change dumpArray
into reuturning a character array. WHat is p
?
That is for starters - Re-read you text book on C and also manual pages on C
Upvotes: 0