Can I use a file pointer to open a file and then assign that pointer to another file pointer in the same program. When I have moved to original pointer to, say end of file, what is the alternate pointer pointing to, at that moment? Also, can i use "fopen" function with two different file pointers in the same program? More specifically, the following two pieces of code do compile correctly but both give segmentation fault as output. What mistake am I doing?
#include<stdlib.h>
void main()
{
FILE *file_ptr, *file_ptr_alt;
int ch, counter=0;
file_ptr = fopen("input.txt","r");
file_ptr_alt = fopen("input.txt","r");
//file_ptr_alt = file_ptr;
while((ch=fgetc(file_ptr))!=EOF)
{
counter++;
}
printf("\nThe val of counter1 is %d\n",counter);
while((ch=fgetc(file_ptr_alt))!=EOF)
{
counter++;
}
printf("\nThe val of counter2 is %d\n",counter);
}
#include<stdlib.h>
void main()
{
FILE *file_ptr, *file_ptr_alt;
int ch, counter=0;
file_ptr = fopen("input.txt","r");
//file_ptr_alt = fopen("input.txt","r");
file_ptr_alt = file_ptr;
while((ch=fgetc(file_ptr))!=EOF)
{
counter++;
}
printf("\nThe val of counter1 is %d\n",counter);
while((ch=fgetc(file_ptr_alt))!=EOF)
{
counter++;
}
printf("\nThe val of counter2 is %d\n",counter);
}
fopen. To your specific question:file_ptr_alt = file_ptr;does not result in a seperate file stream as you seem to think it does. After the firstwhileloopfile_ptrstream will be at the end of the file and so willfile_ptr_alt. That means the secondwhileloop condition will immediately and always be false.input.txtexists and is readable. Besides the compiler warnings you should get, there's nothing wrong.