gpt4 book ai didi

linux - 在 linux 上使用 cat 命令通过标准输入读取二进制数据

转载 作者:太空宇宙 更新时间:2023-11-04 10:28:08 34 4
gpt4 key购买 nike

我正在尝试使用 cat 通过标准输入 (0) 将二进制数据读取到我的程序中命令。我的程序的任务是将二进制更改为整数或 double 并将其写入所需的文件描述符。

当我运行命令时:cat data_int.bin | ./myprogram -d ,我什么也看不到,输入的大小也为 0。但是当我尝试时:./myprogram -d -I 0 0<data_int.bin ,我的程序可以读取字节并成功完成。


我的代码:

#libraries

int main(int argc, char* argv[]) {

int c;
extern char *optarg;
extern int optind;
extern int optopt;

char input_file[100] = { 0 };
int nastavljen_input = 0;
char output_file[100] = { 0 };
int nastavljen_output = 0;
int tip = -1; // 0 - char, 1- int, 2 - double
int fd_in = 0;
int fd_out = 1;
while((c = getopt(argc,argv, ":o:i:O:I:cdf")) != -1) {
switch(c) {
case 'o':
strcpy(output_file,optarg);
nastavljen_output = 1;
fd_out = open(output_file,O_WRONLY);
break;
case 'i':
strcpy(input_file,optarg);
nastavljen_input = 1;
fd_in = open(input_file,O_RDONLY);
break;
case 'O':
fd_out = atoi(optarg);
break;
case 'I':
fd_in = atoi(optarg);
break;
case 'c':
tip = 0;
break;
case 'd':
tip = 1;
break;
case 'f':
tip = 2;
break;
}
}

if(tip > -1) {
struct stat st;
fstat(fd_in, &st); //fd_in would be 0 with cat command
int size = st.st_size; // number of bytes in input file
printf("%d\n",size); // this will print out 0 with cat command

unsigned char buffer[size];
read(fd_in,buffer,size);

...code continues...



标志 -d 用于读取代表整数的字节,-I 用于选择输入文件描述符。在这种情况下,输出是 stdout(1)。

我的问题是,我的代码有问题还是这就是方式 cat命令有效吗?我正在使用 Xubuntu。

感谢您付出的时间和精力,
多门

最佳答案

管道总是有 st_size 0,因为将写入管道的字节流的长度无法提前知晓。

有许多程序在 cat foo | prog 上表现不同和 prog < foo .这就是原因。在第二种情况下,prog在 stdin 上有一个常规文件所以 stat显示大小。同样在第二种情况下,lseek/fseek会工作,但在管道上不会。

如果你想将标准输入的内容读入缓冲区,并且当标准输入是管道时你需要它工作,你必须猜测它的大小,然后跟踪你读取了多少以及何时读取内存不足,再分配一些。 realloc对此有好处。

关于linux - 在 linux 上使用 cat 命令通过标准输入读取二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40917897/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com