I have a file pointer which was assigned in main. In the main, I just open a file to write stuff to it. I want to pass the file pointer to several functions so that they can write to the file. In the fucntion declaration I just add:

somefunc(FILE *file) ?

and when calling pass

File *fptr
.
.
.
somefunc(fptr) ?

Have I got this right so far? With that file pointer I would be able to write to file within those functions.

Recommended Answers

All 5 Replies

>>Have I got this right so far?
Yup -- that's all there is to it. Hopefully you are not writing a multi-threaded program :)

Jobs you are in a right track. Thats right When do this

void foo(FILE *fp);

in main
foo (fp);

When you call foo the address of the file pointer will be copies and sent to the foo function. If you wanted to send it through reference then you will have to do something like this

void foo(FILE **);

in mian
foo(*fp);

But the first method would do what you want.

ssharish

Have I got this right so far? With that file pointer I would be able to write to file within those functions.

It clearly indicates you have done things right!!

What happens if this was a muti-threaded program?

What happens if this was a muti-threaded program?

The same thing that happens when you have a single resource (the file in this case) and multiple threads trying to access it simultaneously. Concurrency safeguards would need to be added to the code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.