Reputation: 191
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.
Upvotes: 7
Views: 62561
Reputation: 33380
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;
}
Upvotes: 12
Reputation: 9850
There's already a system function called write
. Just name your function something else, put a function declaration before you use it, and you'll be fine.
Upvotes: 0
Reputation: 5889
See man 2 write
on linux.
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
That is the prototype. You need to pass an integer file descriptor and not a file pointer.
If you want your own function Change the name to foo_write
or something
Upvotes: 0