gpt4 book ai didi

c - 如何停止从c中的二进制文件读取

转载 作者:太空宇宙 更新时间:2023-11-04 03:57:42 24 4
gpt4 key购买 nike

我正在尝试使用原始 I/O 函数从文件中读取数据并将数据输出到另一个文件但是,我的代码似乎无法工作,我发现 read() 无法终止。但是,我不知道在这种情况下如何终止循环,我的代码是这样的:

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
}

有人可以帮我解决这个问题吗?非常感谢你

最佳答案

read 如果遇到文件结尾,将返回 0:

while(read(infile, &intch, sizeof(unsigned char) > 0){ 
ch = (unsigned char) intch; //Convert
write(outfile, &ch, sizeof(unsigned char));
}

请注意,负值表示错误,因此您可能希望保存 read 的返回值。

关于c - 如何停止从c中的二进制文件读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14927590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com