sergio
sergio

Reputation: 75

fprintf() within a subprogram

Im stuck when trying to write to my file within my subprogram.

void new_page(float *a, float *b, float *c, int *d){
    fprintf(results,"\nPage Totals: %f\t%f\t%f\t%d", *a,*b,*c,*d);
}

I get a warning saying

Warning: incompatible implicit declaration of built-in function 'fprinf' [enabled by default]

"error: 'results' undeclared (first use in this function)"

in main fprintf works fine, its just when it comes to the subprogram/function it wont work. from my understanding it thinks that results is undeclared, so do i have to pass the name or location of the file to make it work?

Upvotes: 0

Views: 1568

Answers (3)

Morpfh
Morpfh

Reputation: 4093

Unless results is global, it is undefined.

From the looks of it, you have opened a file (stream) as results in main. If so it only exists in the scope of main.

Pass it along to the function. Do not recommend to make it global.


It would look like:

void new_page(FILE *results,  float *a, float *b, float *c, int *d){
    fprintf(results,"\nPage Totals: %f\t%f\t%f\t%d", *a,*b,*c,*d);
}

Also; if you have this function in a separate file then main(), where, as you say fprintf works - you have to include stdio.h in that file as well.


Edit: Sounds like you are doing something wrong with that function signature and prototype etc.

As a simple example (without needed checks on fopen etc):

#include <stdio.h>

void foo(FILE * fp)
{
    fprintf(fp, "HELLO\n");
}

int main(void)
{
    FILE *fp;

    fp = fopen("blabla", "w");
    foo(fp);
    fclose(fp);

    return 0;
}

Also; you say your compiler is not complaining. Are you using extensive warnings? If not you should. Ie GCC:

$ gcc -Wall -Wextra -pedantic -o my_prog my_source.c

I usually also add -std=c89, or if needed, -std=c99.

Then run it wit valgrind:

$ valgrind ./my_prog

These two steps will give you lots of hints and clues to where things could be wrong.

Upvotes: 1

Keith Thompson
Keith Thompson

Reputation: 263177

To solve the fprintf warning, you need to add

#include <stdio.h>

near the top of your source file.

The results error is different; you can either make it global or pass it as an argument to your new_page function.

Making a variable global (i.e., defining outside any function, including main) is generally poor style, but if results is a FILE* that you're going to be using throughout your program, it's not unreasonable to make it global.

Upvotes: 1

laltin
laltin

Reputation: 1152

There ara more than one solutions here.

  1. You can pass the file handler to the function.
  2. You can use printf to write into a file. But if you do that you cannot write to the screen again. Search freopen

Upvotes: 0

Related Questions