我目前正在编写一个小的虚拟程序来尝试正确使用 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[一些奇怪的符号]”。所以我不确定在哪里处理这个错误,或者为什么它在读取时仍然错误地放入缓冲区。