Search code examples
cfgets

How can I refer to a file as the stream for fgets()?


fgets() returns a string from a provided stream. One is stdin, which is the user input from the terminal. I know how to do this, but if I am using compiled c code in applications, this is not very useful. It would be more useful if I could get a string from a file. That would be cool. Apparently, there is some way to provide a text file as the stream. Suppose I have the following code:

#include <stdio.h>

int main(int argc, const char *argv){
    char *TextFromFile[16];
    fgets(TextFromFile, 16, /*stream that refers to txt file*/);
    printf("%s\n", TextFromFile);
    return 0;
}

Suppose there is a text file in the same directory as the c file. How can I make the printf() function print the contents of the text file?


Solution

  • Later I found out the problem. fopen is stupid. Using ./file.txt or others will not work. I need to use the whole file path to do it.

    FILE (*File) = fopen("/home/asadefa/Desktop/txt.txt", "r");
    char FData[0x100];
    memset(FData, '\0', 0x100);
    for(z = 0; z < 0x100; ++z) {
        fgets(FData, 0x100, File);
    }
    fclose(File);
    

    I should have noted that the full file path is used.