【发布时间】:2016-12-01 18:29:48
【问题描述】:
我正在尝试使用cat 命令通过stdin (0) 将二进制数据读取到我的程序中。我的程序的任务是将二进制更改为整数或双精度并将其写入所需的文件描述符。
当我运行命令: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。
感谢您的时间和精力,
圆顶
【问题讨论】: