0

我目前正在编写一个小的虚拟程序来尝试正确使用 c 中的读取。我制作了一个名为 readdata 的小函数来读取文件描述符并存储在缓冲区中,然后返回读取的字节数。我的问题是我正在尝试正确处理错误并捕获事物,以便没有缓冲区溢出,但我一直在做一些事情。

这是测试仪:

#include <stdio.h>
#include <string.h>
#include <unistd.h>

#define BUFSIZE 10

int readdata(int fd, char *buf, int bsize);

int main(void) {
   char buf[BUFSIZE];
   int returnval;
   int length;
   returnval = readdata(STDIN_FILENO, buf, BUFSIZE);
   printf("%s",buf);
   length = strlen(buf);
   fprintf(stderr,"The return value is %d\n", returnval);
   fprintf(stderr,"The string is %s\n",buf);
   fprintf(stderr,"The length of the string is %d\n",length);
   return 0;
}

这是小功能:

#include <stdio.h>
#include <stdlib.h>

int readdata(int fd, char *buf, int bufsize){
   int n = 0;
   if(fd < 0){
     return 1;
   }

   while((n=read(fd,buf,(bufsize-1)))>0){
      if(n == -1) {
         perror( "Read failed" );
         return 1;
      }
      else{
         buf[bufsize] = 0;
         return n;
      }
   }
}

如果我跑

 cc -o test test.c readdata.c

然后放

echo "Hello" | ./test

它工作正常。但是,如果我像这样通过 bufsize 限制:

echo "1234567891" | ./getdatatest

它给了我这个奇怪的输出,上面写着“字符串是 123456789[一些奇怪的符号]”。所以我不确定在哪里处理这个错误,或者为什么它在读取时仍然错误地放入缓冲区。

4

1 回答 1

1

你知道read()返回的字符比你要求的少吗?此外,buf[bufsize]刚刚过去的结尾buf。您的readdata函数还应该返回类似-1on error 的信息,而不是1这样您就可以区分条件“读取一个字节”和“IO 错误”。</p>

考虑这样的事情:

for (;;) {
    n = read(fd, buf, (bufsize - 1));

    if(n == -1) {
       perror( "Read failed" );
       return -1;
    } else {
       buf[n] = 0;
       return n;
    }
}
于 2016-01-23T18:41:10.767 回答