【发布时间】:2018-07-04 20:36:20
【问题描述】:
我在将来自标准输入的文件存储到缓冲区时遇到问题。
这是我的代码:
//Go to the end of stdin and calculate the number of elements
int num;
fseek (stdin, 0, SEEK_END);
num = ftell (stdin);
//If there is a file in the standard input
if(num > 0) {
int resRead;
//Read the file and store it into buffer
if((resRead = read(STDIN_FILENO,buffer,num))){
fprintf(stderr, "Error: Could not store the input into buffer\n");
}
//Display the buffer
for (int i = 0; i < num; ++i)
{
printf("%c\n",buffer[i]);
}
}
当我启动我的代码时:./interpreter
我必须明确我的文件有内容,当我检查 num 的值时,它与文件中的字符数完全对应。
有什么想法吗? :)
谢谢!!
【问题讨论】:
-
你到底为什么要在标准输入上使用
fseek()和ftell()?我无法想象这会达到你的预期。 -
@ChrisTurner:如果标准输入是从文件重定向的(似乎是这种情况),那可以工作......
-
@MaxUt:有两个主要问题:(1)您将 C 库函数(
fseek、ftell等)与内核函数(read等)混合在一起,这可能会导致问题..(2)您正在寻找文件的末尾,然后尝试从中读取 - 所以您没有得到任何数据,因为没有剩下的了!您可能想回到起点。 (除此之外,正如其他人指出的那样,如果您需要在输入中查找,通常最好在命令行上获取文件名并使用open()或fopen()- 但如果您知道 stdin 将always从文件重定向,你的应该工作)。 -
@psmears 非常感谢。除了使用 fseek() 检查之外,您知道如何确保有一个文件重定向到标准输入吗?