fgets()从提供的流中返回一个字符串。一个是stdin,它是来自终端的用户输入。我知道该怎么做,但是如果我在应用程序中使用编译后的c代码,这将不是很有用。如果可以从文件中获取字符串,则将更加有用。那会很酷。显然,有一些方法可以提供文本文件作为流。假设我有以下代码:
#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;
}
假设在与c文件相同的目录中有一个文本文件。如何使printf()函数打印文本文件的内容?
答案 0 :(得分:2)
鉴于以下定义;
字符* 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
在函数中,语句:
FILE *fp = fopen(fileSpecToSource, "r");//file location is local to source directory.
如果成功(即fp!= NULL),则fp
可用作以下命令中的 stream 参数:
fgets(TextFromFile, 16, fp);
答案 1 :(得分:1)
后来我发现了问题所在。 fopen
很愚蠢。使用./file.txt
或其他方法无效。我需要使用整个文件路径来做到这一点。
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);
我应该注意到使用了完整的文件路径。