使用read(...)write(...)在C中读写文件

时间:2013-03-30 19:17:22

标签: c

这些命令应该返回读取或写入的字节。 目前,我正在尝试一次读取和写入100个字符。 当我使用read(fd,buffer,100)时,我会读取99个字符。当我使用read(fd,buffer,101)时,我会读取100个字符。有什么问题?

我应该从源代码中读取100个字符并将它们写入destination1。然后,我应该从同一个源读取50个字符到destination2。 在前几个循环之后,读取和传递是不准确的。第三个循环出现问题。 请查看:

  [Step 2] Prcs_P2.c: Copy the contents of source.txt into destination1.txt and 
  destination2.txt as per the following procedure.

  1. Read the next 100 characters from source.txt, and among characters read, 
  replace each character ’1’ with character ’A’ and all characters are then 
 written in destination1.txt
 2. Then the next 50 characters are read from source.txt, and among characters
 read, replace each character ’2’ with character ’B’ and all characters are
 then written in destination2.txt
 3. The previous steps are repeated until the end of file source.txt.
 The last read may not have 100 or 50 characters.
 -------------
 It's copying characters irregularly. sometimes more than 100 | 50 and sometimes less.

 int main() {

    //const int sizeBuff=100;

    char buffer[105];   //used to carry information in packets of 10
    int temp=0;     //temp variable to check for errors
    int charCount=0;


    int i=0;

//----------------------------------------
    //charCount=read(sourceFile, buffer , 101 );
    while( charCount=read(sourceFile, buffer , 100) >0){    //needed 101 as last arg instead of 100. DUnno why?

        i=0;
        while(i<charCount){
            if (buffer[i]=='1')
                buffer[i]='A';
            i++;
        }

        if(write( destinationFile, buffer,charCount)==-1)       //write(...) returns the number of bytes written to destinationFile
                                //-1 depicts error in the function and 0 is returned upon end of file
        {
            printf("\nWrite fail.\n");
            perror("Error");                //Prints error, if found while writing.
        }
        memset(buffer, 0, 105);     //CLEARS BUFFER

        i=0;
        charCount=read(sourceFile, buffer , 50 );   //reads 50 bytes at a time      //need flag for error
        while(i<charCount){
            if (buffer[i]=='2')
                buffer[i]='B';
            i++;
        }

        temp=write( destinationFile2, buffer, charCount);       //write(...) returns the number of bytes written to destinationFile
        if(temp==-1)                        //-1 depicts error in the function and 0 is returned upon end of file
        {
            printf("\nWrite fail.\n");
            perror("Error");                //Prints error, if found while writing.
        }

        memset(buffer, 0, 105);
    }//while loop ends

    close(destinationFile);
    close(destinationFile2);
    close(sourceFile);
    //------PART 1 ENDS-------------

    //------PART 2 STARTS------------



}

1 个答案:

答案 0 :(得分:4)

charCount=read(sourceFile, buffer , 100) >0

这会将charCount设置为0或1.您想要

(charCount = read(sourceFile, buffer , 100)) > 0