c - 如何在 C 中将 stdin 的值存储到数组中?

标签 c stdin

我面临着将来自标准输入的文件存储到缓冲区中的问题。

这是我的代码:

//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/

相关文章:

curl - 通过 cURL 从 stdin 上传数据作为具有特定名称的文件

c++ - 使用标准输入重定向输入

c - C中的递归函数是如何工作的

c - 将 Gtk Widgets 结构传递给回调函数

c - 如何正确安装libpng?

c - STDIN 缓冲区和 getchar() 指针在连续调用期间如何变化?

c - 16 位机器上可以使用 32 位整数吗?

c - 如何在 x32 和 x64 中保持结构体大小不变?

python - 如何将数据重定向到 "getpass"之类的密码输入?

security - 如何将变量的值传递给命令的标准输入?