C file pointer assignment to another file pointer

Viewed 238

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

In this case assigning a FILE pointer to another FILE pointer is pretty pointless. Both pointers will point to the exact same file structure.

Considering this code snippet:

file_ptr = fopen("input.txt","r");
file_ptr_alt = file_ptr;

now you can use file_ptr_alt or file_ptr for your file operations. They will do exactly the same thing.

E.g

a = fgetc(file_ptr_alt);
b = fgetc(file_ptr);

will do exactly the same thing as:

a = fgetc(file_ptr);
b = fgetc(file_ptr_alt);

if you've got to the end of the file with file_ptr, file_ptr_alt will also "point" to the end of the file.


With this code snippet it's a different story:

file_ptr = fopen("input.txt","r");
file_ptr_alt = fopen("input.txt","r");

Now file_ptr and file_ptr_alt are totally independent, if you've got to the end of the file with file_ptr, file_ptr_alt will still "point" to the beginning of the file.


Now for the totally unrelated question about the segmentation fault:

It's certainly because you dom't check if fopen fails. If fopen fails for example because the file you try to open does not exist (this happens very often), it returns a NULL FILE pointer. Now using a NULL file pointer with fgetc or any other related file operation, you'll get undefined behaviour, which most of the time manifests itself as segmentation fault.

You want something like this:

file_ptr = fopen("input.txt","r");
if (file_ptr == NULL)
{
  printf("File cannot be opned\n");
  ... take further action, but don't try to do anything
      with file_ptr

}
Related