Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't open a text file in C from which i want to read text as data and write it into an array

#include <stdio.h>

int main(void){

    FILE *ptr;
    ptr = fopen("example.txt", "r");
    if (ptr == NULL){
        printf("File not opened or found");
        return 1;
    }
    
    char str[20];
    fgets(str, sizeof(str), ptr);
    printf("Read text from example.txt is: %s\n", str);

    return 0;
}

I’m new to C and i got quite a lot confused about the basic file access logic in C, my first question is why did fgets() function accept ptr instead of *ptr as the third argument? Why the address of the FILE struct instead of what it references to?
When I run the code i always get the error in the if body, I’m running a windows machine and can’t get my C code to retrieve example.txt using fopen() function. Any help would be appreciated.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The standard stream function to handle files and such, declared in <stdio.h> use pointers to opaque FILE structures allocated by the library. The details of the implementation are kept private to the library, all the program needs are FILE pointers returned by fopen() or freopen() and passed as argument to input and output functions.

The library functions update the FILE structure appropriately to implement the buffering scheme and other translation functionalities. If the FILE structure was passed directly, it could not be updated as structures are passed by value in C so the library function would just receive a copy of the structure and any updates would be lost as soon as the function returns.

This method is very general and is used by many programming languages behind the scenes. Java objects are typically passed as pointers to methods. The same for javascript objects and arrays. Functions receiving object references in C++ basically get pointers that are guaranteed to never be null. In these circumstances, object property access via the . operator are translated as pointer dereferencing with some or no additional runtime checks and lookups.

In your exmaple, you say the file cannot be opened: producing a more informative error message is a good habit to help track such failures. The file cannot be open probably because it is not present in the current directory at run time.

You should also check for potential failure in fgets() and close the stream with fclose().

#include <errno.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    FILE *ptr = fopen("example.txt", "r");
    if (ptr == NULL) {
        fprintf(stderr, "Cannot open example.txt: %s\n", strerror(errno));
        return 1;
    }
    
    char str[100];
    if (fgets(str, sizeof(str), ptr)) {
        printf("Read text from example.txt is: %s\n", str);
    } else {
        printf("File example.txt is empty\n");
    }
    fclose(ptr);
    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading