How to use FILE as parameter for function in C?

I am learning C and I come from a Java background. I would be grateful if I had any 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? Thank you for your time.

+4
source share
3 answers

You are missing a function prototype for your function. In addition, write declared in unistd.h , so you get the first error. Try renaming this to my_write or something like that. You really need the stdio.h library as well as a side note if you do not plan to use other functions later. I added error checking for fopen as well as return 0; , which should enclose 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; } 
+7
source

See man 2 write on linux.

 #include <unistd.h> ssize_t write(int fd, const void *buf, size_t count); 

This is a prototype. You need to pass an integer file descriptor, not a file pointer. If you want your own function to change the name to foo_write or something

0
source

There is already a write system function. Just call your function something else, place a function declaration before using it, and everything will be fine.

0
source

All Articles