Reputation:
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?
Upvotes: 0
Views: 856
Reputation:
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.
Upvotes: 0
Reputation: 23218
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);
Upvotes: 2