#Two pointers to the same file in C
9 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.
#include <stdio.h>
int main(){
FILE* fp1 = fopen("testfile.txt","w+");
FILE* fp2 = fopen("testfile.txt","w+");
char c = 'X';
char d = 'Y';
putc(c, fp1);
putc(d, fp2);
printf("%p %p", fp1, fp2);
}
Also, where can I find detailed info about the FILE struct and what each of its members means?
Opening the same file twice like that just opens two separate streams to it. It's not useful but it won't break anything either. The reason your file ends up having Y as its contents is because you open the streams in a mode that resets the write position:
w+ Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
This means that you write X but then write Y with another stream that truncates the same file i.e. overwrites it with Y. If you do both writes with only one stream you'll end up writing XY. Or, if you open the streams in "a+" mode then the streams will both append to the end of the file, and you get XY as well.
About the FILE struct: its address is irrelevant, and the exact layout and contents of it are not in any way part of the public API. It's all implementation-specific and completely depends on whatever libc your system uses. You're not meant to access it, it's simply an opaque pointer that you pass around to the libc stream API functions.
(What I mean by the address being irrelevant: the only thing that printf("%p\n%p\n", fp1, fp2) tells you is whether or not those two pointers are the same. There's nothing more to learn by looking at the raw address. It has nothing to do with the file itself. The FILE pointer is simply an internal libc handle.)