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);
}