[英]How to properly error trap read in c to get byte number from a file descriptor
我目前正在編寫一個小型虛擬程序,以嘗試使用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 [一些奇怪的符號]”。 因此,我不確定在哪里處理該錯誤,或者為什么在讀取時仍然錯誤地將其放入緩沖區。
您是否知道read()
返回的字符數少於您請求的字符數? 另外, buf[bufsize]
剛超過buf
的結尾。 您的readdata
函數還應在出錯時返回類似於-1
而不是1
以便您可以區分條件“讀取一個字節”與“ IO錯誤”。
考慮這樣的事情:
for (;;) {
n = read(fd, buf, (bufsize - 1));
if(n == -1) {
perror( "Read failed" );
return -1;
} else {
buf[n] = 0;
return n;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.