2015-04-14 234 views
0

我试图使用C中的读取功能。 (此功能: http://pubs.opengroup.org/onlinepubs/009695399/functions/read.html)。 当我从包含相同内容('H')的不同文件读取时。 读取函数被调用后,缓冲区不相等,但是当我尝试以%c格式打印时,它们都会打印出'H'(正确的输出)。C从文件描述符中读取

这里是我的代码:

#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; 
} 
+2

我不明白这个问题。为什么你打印它们时不包含相同的价值? – Barmar

+0

你的意思是“缓冲区不等于” –

+3

你对“buff1”和“buff2”的声明是错误的。它们应该是'unsigned char',而不是'unsigned char *'。 – Barmar

回答

3

界定缓冲器为unsigned char buff1[SIZE+1]unsigned char buff2[SIZE+1]。没有必要定义指针数组。顺便说一句,没有必要分配SIZE + 1字节,因为read不会在末尾添加零字节。当你说“缓冲区是X字节”时,它是X字节。更好地使用read(fdin1, buff1, sizeof buff1)

相关问题