I'm trying to use raw I/O functions to read from a file and output the data to another file however, it seems that my code cannot work, which I figured out is that the read() cannot be terminated. However, I don't know how to terminate the loop in the case, my code is like this:
int main(){
int infile; //input file
int outfile; //output file
infile = open("1.txt", O_RDONLY, S_IRUSR);
if(infile == -1){
return 1; //error
}
outfile = open("2.txt", O_CREAT | ORDWR, S_IRUSR | S_IWUSR);
if(outfile == -1){
return 1; //error
}
int intch; //character raed from input file
unsigned char ch; //char to a byte
while(intch != EOF){ //it seems that the loop cannot terminate, my opinion
read(infile, &intch, sizeof(unsigned char));
ch = (unsigned char) intch; //Convert
write(outfile, &ch, sizeof(unsigned char));
}
close(infile);
close(outfile);
return 0; //success
}
could somebody helps me on the problem? THank you a lot
read
will return 0
if you encounter the end of file:
while(read(infile, &intch, sizeof(unsigned char) > 0){
ch = (unsigned char) intch; //Convert
write(outfile, &ch, sizeof(unsigned char));
}
Note that a negative value indicates an error, so you might want to save the return of read
.
intch is uninitialized 4 (or sometimes 8) bytes. You are only loading 1 byte into intch, and leaving the remaining bytes uninitialized. You then compare EOF with all of intch, which has not been fully initialized.
Try declaring intch as a char.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.