![](/img/trans.png)
[英]Read/write exactly N bytes from/to file descriptor with C on Unix
[英]C read from a file descriptor
我試圖在C中使用讀取功能。(此功能: http : //pubs.opengroup.org/onlinepubs/009695399/functions/read.html )。 當我從包含相同內容('H')的不同文件讀取時。 調用讀取函數后,緩沖區不相等,但是當我嘗試以%c格式打印時,都打印'H'(正確的輸出)。
這是我的代碼:
#include <stdio.h>
#include <sys/fcntl.h>
#include <errno.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
/* #DEFINES */
#define ADD1 "text1.txt"
#define ADD2 "text2.txt"
#define SIZE 1
int main()
{
// Initializing
int fdin1=0,fdin2=0;
int r1=1,r2=1;
unsigned char * buff1[SIZE+1];
unsigned char * buff2[SIZE+1];
fdin1 = open(ADD1,O_RDONLY);
if (fdin1 < 0) /* means file open did not take place */
{
perror("after open "); /* text explaining why */
exit(-1);
}
fdin2 = open(ADD2,O_RDONLY);
if (fdin2 < 0) /* means file open did not take place */
{
perror("after open "); /* text explaining why */
exit(-1);
}
// Reading the bytes
r1 = read(fdin1,buff1,SIZE);
r2 = read(fdin2,buff2,SIZE);
// after this buff1[0] and buff2[0] does not contain the same value!
// But, both r1 and r2 equals to 1.
printf("%c\n",buff1[0]);
printf("%c\n",buff2[0]);
// It prints the correct output (both H)
close(fdin1);
close(fdin2);
return 0;
}
將緩沖區定義為unsigned char buff1[SIZE+1]
和unsigned char buff2[SIZE+1]
。 不必定義指針數組。 順便說一句,沒有必要分配SIZE + 1
個字節,因為read
末尾不會添加零字節。 當您說“緩沖區是X字節”時,它是X字節。 最好使用read(fdin1, buff1, sizeof buff1)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.