How do I use a FILE as a parameter for a function in C?
51,327
You are lacking a function prototype for your function. Also, write
is declared in unistd.h
so that is why you get the first error. Try renaming that to my_write
or something. You really only need the stdio.h
library too as a side note, unless you plan on using other functions later. I added error checking for fopen
as well as return 0;
which should conclude every main function in C.
Here is what I would do:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
void my_write(FILE *fp, char *str)
{
fprintf(fp, "%s", str);
}
int main(void)
{
char *str = "test text\n";
FILE *fp;
fp = fopen("test.txt", "a");
if (fp == NULL)
{
printf("Couldn't open file\n");
return 1;
}
my_write(fp, str);
fclose(fp);
return 0;
}
Author by
Giga Tocka
Updated on July 21, 2022Comments
-
Giga Tocka almost 2 years
I am learning C and I come from a Java background. I would appreciate it if I could have some guidance. Here is my code:
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int main(void) { char *str = "test text\n"; FILE *fp; fp = fopen("test.txt", "a"); write(fp, str); } void write(FILE *fp, char *str) { fprintf(fp, "%s", str); }
When I try to compile, I get this error:
xxxx.c: In function ‘main’: xxxx.c:18: warning: passing argument 1 of ‘write’ makes integer from pointer without a cast /usr/include/unistd.h:363: note: expected ‘int’ but argument is of type ‘struct FILE *’ xxxx.c:18: error: too few arguments to function ‘write’ xxxx.c: At top level: xxxx.c:21: error: conflicting types for ‘write’ /usr/include/unistd.h:363: note: previous declaration of ‘write’ was here
Any thoughts? Thanks for your time.