如何正确错误地读取C中的陷阱以从文件描述符中获取字节数 [英] How to properly error trap read in c to get byte number from a file descriptor

查看:107
本文介绍了如何正确错误地读取C中的陷阱以从文件描述符中获取字节数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently writing a small dummy program to try and get the hang of properly using the read in c. I made a small function called readdata to read from the file descriptor and store in a buffer then return the number of bytes read. My problem is I am trying to correctly error handle and trap things so that there is no buffer overflow but I keep doing something from.

这是测试人员:

#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限制,如下所示:

It works fine. But if I pass the bufsize limit like this:

echo "1234567891" | ./getdatatest

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

It gives me this weird output where it says "the string is 123456789[some weird symbol]" . So I am not sure where to handle this error or why it is still incorrectly putting in the buffer when reading.

推荐答案

您知道read()返回的字符少于您请求的字符吗?另外,buf[bufsize]刚好在buf的结尾.您的readdata函数还应该在发生错误时返回类似-1的信息,而不是返回1,以便您可以区分条件读取一个字节"与"IO错误".

You do know that read() can return less characters than you requested? Also, buf[bufsize] is just past the end of buf. Your readdata function should also return something like -1 on error instead of 1 so you can distinguish the condition "one byte read" from "IO error."

考虑这样的事情:

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

    if(n == -1) {
       perror( "Read failed" );
       return -1;
    } else {
       buf[n] = 0;
       return n;
    }
}

这篇关于如何正确错误地读取C中的陷阱以从文件描述符中获取字节数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆