对于一项作业,我们必须创建功能类似于 cat 命令的 C 程序。第一次提交要求它模仿 cat 的非常小的操作....即打印到输出、重定向。我遇到的问题是,一个要求是在驻留在 USB 驱动器上的输出文件丢失的情况下打印错误,即在将 stdout 重定向到它时拔出 USB。
如何捕获此类错误,以及如何针对该特定错误执行测试用例??
非常感谢....真的不知道
更新代码模板
int main(){
char c;
while((c = getchar()) != EOF){
putchar(c);
// Ensure newly created file exists
}
return EXIT_SUCCESS;
}
最佳答案
假设您正在使用 fprintf()
,来自 man pages :
On success, the total number of characters written is returned.
所以:
- 将要写入的
char
数组的大小存储到变量x
- 如果
fprintf()
小于x
,则写入中断。 - 优雅地退出
编辑:
我在想两件事:
1:当putchar()
失败时,表示写入文件时出错。由于写入一个字节不会花费很长时间,所以这应该不太可能,因为一旦字节被写入(或您假设),它将处于安全状态。
你可以这样做
if(putchar(c) == EOF){
//write error
}
2:如果您在检测到文件被删除时被要求立即退出,那么您需要监控该目录。幸运的是,您只查看一个目录。然而,while
循环妨碍了事情的进行,因为 getchar()
是一个阻塞函数(在某些事情发生之前无法返回)。你应该使用 inotify监控目录,那么大概是poll轮询 inotify()
的文件描述符。当我这样做时,我使用了 select因为我们被迫。
关于如何使用 inotify()
监控目录的一些想法
int length, i = 0;
char buffer[EVENT_BUF_LEN];
memset(buffer, 0, EVENT_BUF_LEN*sizeof(char));
//init inotify
fd = inotify_init();
if(fd < 0){
perror("inotify init");
}
//add directory to watch list
wd = inotify_add_watch(fd, path , IN_DELETE |
IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO);
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
//wait for event, since read() blocks
length = read( fd, buffer, EVENT_BUF_LEN );
if ( length < 0 ) {
perror("zero event length");
}
struct inotify_event *event;
while (i < length){
//cast the event to a char buffer
event = (struct inotify_event*) &buffer[i];
if (event->len){
//this was a custom function of mine
storeEvent(event);
}
i += EVENT_SIZE + event->len;
}
您必须检查在添加目录时要使用哪些属性(如 IN_DELETE
或 IN_MODIFY
),因为它们将决定什么会触发 inotify()
事件。请注意,此代码将仅检测一个事件,并在 read()
语句处阻塞。
关于cat 终端,检查 usb 是否已移除(错误)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15170824/