我面临着将来自标准输入的文件存储到缓冲区中的问题。
这是我的代码:
//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 < file.txt时,我没有得到缓冲区的内容。
我必须准确地说我的文件有内容,当我检查 num 的值时,它与文件中的字符数完全对应。
有什么想法吗? :)
谢谢!!
最佳答案
操作系统级流式传输或文件间接到二进制文件在这种情况下不起作用,除非您有从程序中的标准输入读取代码的文件。
更好的选择是将文件保留在目录中并将文件位置作为参数传递给程序。并使用fopen()读取文件。
关于c - 如何在 C 中将 stdin 的值存储到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48445524/