C/problems with function that uses a FILE* pointer
Expert: Narendra - 11/22/2004
QuestionNerendra:
I have no problem when I initialize the FILE pointer in the main code as you done in your example. There is no other way? Because I initialize ( FILE *fp = fopen("file1.txt", "r"); INSIDE myfunc! Should I use FILE** and then, when I call, write: "myfunc(&myfp)".?
GUESS WHAT? I find the way! I use this code:
#include <stdio.h>
void myfunc(FILE **myfp)
{
*myfp = fopen("file.txt", "r");
printf("%x\n", myfp);
return;
}
main()
{
char c;
FILE *fp;
myfunc(&fp);
printf("%x\n", fp);
c=getc(fp);
printf("%c\n", c);
return 1;
}
THE AMAZING THING IS THAT, AFTER myfunc I GET ANOTHER POINTER BUT I CAN READ THE FIRST CHAR OF file (in my case I get a #)!
In this printf("%x\n", myfp);(inside myfunc) I get 12ff88
An printf("%x\n", myfp); in MAIN get: 40b6e8 !
Why if they are different I can read file.txt without problems?
Thanks again!
Willy from Argentina.
-------------------------
Followup To
Question -
I am using:
Program: Texpad
Compile Program: Borland C++ 5.5.1 for Win32
Hardware: AMD-K6 3D processor, Pc-Chips motherboard, 64MB ram.Windows 98SE.
My problem:
I have to create a program that converts ".txt" files in binary files (".bin") and the other way round.
I made a function to open the files ... Its prototype is "void OpenFiles(FILE*arch1, FILE*arch2)"
Then I declare FILE *file1 and FILE* file2 in main code, and call that function which is in main code too.
If y print the FILE pointer with "printf("pointer, where are you?%p",file1);" inside the function!, I get something like "0040BCD7".
Now, just before that function call process(always in main part but now outside the function) I print again the pointer: "printf("pointer, where are you now?%p",file1);" and I always get "0000000"!. The same happens with file2.
What can be wrong? Should I use &FILE*file... or something like that?
Thanks for helping me.
Willy from Argentina.
Answer -
>I get something like "0040BCD7"
This is OK. Nothing wrong there.
After passing it to function also you should get the same.
I will give you a small example which you can try:
#include <stdio.h>
myfunc(FILE *myfp)
{
printf("%x\n", myfp);
}
main()
{
FILE *fp = fopen("file1.txt", "r");
printf("%x\n", fp);
myfunc(fp);
}
Check whether it prints different values!?
-ssnkumar
AnswerThere is a small mistake in your code.
Inside the function since you are having FILE **, you must print the adress of *myfp.
Here is the corrected code:
#include <stdio.h>
void myfunc(FILE **myfp)
{
*myfp = fopen("file.txt", "r");
printf("%x\n", *myfp);
return;
}
int main()
{
char c;
FILE *fp;
myfunc(&fp);
printf("%x\n", fp);
c=getc(fp);
printf("%c\n", c);
return 1;
}
Hope this clears your doubt......
-ssnkumar