如何解决在我的 C++ 简单缓冲区代码中,退出 3 和 4 的错误语句应该是什么?
我需要输入上面的错误语句 3 和 4,然后实际强制代码转到这些错误语句,以便我可以通过屏幕截图证明它们正在工作。但是,我无法弄清楚每个应该是什么。我最初的想法是“无法为 3 创建输出文件,而对于 4,您要读取的文件为空”,但我似乎无法触发这些错误,所以我觉得这是不正确的。>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#define BUF_SIZE 500
#define OUTPUT_MODE 0700
int main(int argc,char *argv[])
{
int in_file,out_file;
int read_size = 1,write_size;
char buf[BUF_SIZE];
if (argc != 3){
cout<<"The command-line input does not contain 3 arguments"<<endl;
exit(1);
}
in_file= open(argv[1],O_RDONLY);
if (in_file < 0) {
cout<<"The file you are trying to copy from doesnt exist"<<endl;
exit(2);
}
out_file = creat(argv[2],OUTPUT_MODE);
if (out_file < 0) {
cout<<"Error statement 3"<<endl;
exit(3);
}
while (read_size > 0) {
read_size = read(in_file,buf,BUF_SIZE);
if (read_size <0){
cout<<"Error statement 4"<<endl;
exit(4);
}
write_size = write(out_file,read_size);
if (write_size<=0){
close(in_file);
close(out_file);
cout<<"Reading and writing from and to files is complete"<<endl;
exit(5);
}
}
}
解决方法
了解这些函数如何/将会失败的方法是阅读它们的文档。
https://man7.org/linux/man-pages/man2/read.2.html https://man7.org/linux/man-pages/man2/open.2.html
(注意,creat 的文档说它等同于使用特定参数调用 open)
在底部,它列出了将要设置的 errno 以及原因。 例如,在只读磁盘上打开将失败。
,大多数标准库函数都会设置 errno 来告诉你它们失败的原因。使用该信息,并将错误消息写入 stderr:
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#define OUTPUT_MODE 0700
int
main(int argc,char *argv[])
{
int in_file,out_file;
int read_size,write_size;
char buf[BUFSIZ];
if (argc != 3){
cerr << "Missing arguments" <<endl;
exit(EXIT_FAILURE);
}
in_file= open(argv[1],O_RDONLY);
if( in_file < 0 ){
cerr << argv[1] << ": " << strerror(errno) << endl;
exit(EXIT_FAILURE);
}
out_file = creat(argv[2],OUTPUT_MODE);
if( out_file < 0 ){
cerr << argv[2] << ": " << strerror(errno) << endl;
exit(EXIT_FAILURE);
}
while( (read_size = read(in_file,buf,BUFSIZ)) > 0 ){
const char *s = buf;
do {
write_size = write(out_file,s,read_size);
read_size -= write_size;
if( write_size <= 0 ){
cerr << argv[2] << ": " << strerror(errno) << endl;
exit(EXIT_FAILURE);
}
s += write_size;
} while( read_size > 0);
}
if( read_size < 0 ){
cerr << argv[1] << ": " << strerror(errno) << endl;
exit(EXIT_FAILURE);
}
close(in_file);
close(out_file);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。