0
votes

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?

2
Warning: char* x[16] is an array of sixteen character pointers, not an array of sixteen characters. If this code compiles quietly you need to turn on more warnings because that fgets call is invalid.tadman
Your question states the text file is in the same directory as the C source file. There is in general no way for the running program to know the directory of the C source file from which it was compiled. You will have to make some sort of arrangement to convey this information or to put the text file in a known location. (Keeping it in the same directory as the executable file is a possibility, as that directory can be derived from the argv[0] passed to main.)Eric Postpischil
@NoDataFound How is it even remotely a duplicate?user12211554
Because you say 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? You don't ask how to read the content of any file on the filesystem (which is answered by ryyker). And if you want to read the whole file that's another matter involving buffer and reallocation which is answered by this one: stackoverflow.com/questions/3381080/…NoDataFound

2 Answers

2
votes

Given the following is defined;

char *TextFromFile[16];

char TextFromFile[16]; //note "*" has been removed 
const char fileSpecToSource[] = {"some path location\\someFileName.txt"};//Windows
const char fileSpecToSource[] = {"some path location/someFileName.txt"};//Linux

From within a function, the statement:

FILE *fp = fopen(fileSpecToSource, "r");//file location is local to source directory.

if successful (i.e. fp != NULL), fp can be used as the stream argument in:

fgets(TextFromFile, 16, fp);
1
votes

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.