这些命令应该返回读取或写入的字节。 目前,我正在尝试一次读写 100 个字符。 当我使用 read(fd, buffer, 100) 时,我读取了 99 个字符。当我使用 read(fd, buffer, 101) 时,我读取了 100 个字符。有什么问题?
我应该从源代码中读取 100 个字符并将它们写入目标 1。然后,我应该从同一源读取 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------------
}
最佳答案
charCount=read(sourceFile, buffer , 100) >0
这会将 charCount
设置为 0 或 1。您想要
(charCount = read(sourceFile, buffer , 100)) > 0
关于c - 使用 read(...) write(...) 在 C 中读取和写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15722457/