Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a FILE as a parameter for a function in C?

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.

like image 829
Giga Tocka Avatar asked Apr 01 '13 05:04

Giga Tocka


1 Answers

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;
}
like image 52
squiguy Avatar answered Sep 21 '22 16:09

squiguy