使用系统调用open read write,完成一个C语言程序:该程序接收两个参数,参数1作为要读写的文件,参数2作为标志位,标识是读还是写。功能完成对参数1所示文件的读写,该文件的内容为 “学号 MYFILE”,其中学号填为自己的学号。
时间: 2024-03-25 11:40:16 浏览: 54
好的,我来为您完成这个程序。以下是代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define BUFSIZE 1024
int main(int argc, char *argv[]) {
int fd, mode;
char buf[BUFSIZE];
char *filename = argv[1];
char *content = "学号 123456789"; // 将学号填写在这里
size_t len = strlen(content);
if (argc != 3) {
printf("Usage: %s <filename> <mode>\n", argv[0]);
exit(EXIT_FAILURE);
}
mode = atoi(argv[2]);
if (mode != O_RDONLY && mode != O_WRONLY) {
printf("Invalid mode!\n");
exit(EXIT_FAILURE);
}
fd = open(filename, mode);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
if (mode == O_RDONLY) {
ssize_t nread = read(fd, buf, BUFSIZE);
if (nread == -1) {
perror("read");
exit(EXIT_FAILURE);
}
buf[nread] = '\0';
printf("%s\n", buf);
} else {
ssize_t nwrite = write(fd, content, len);
if (nwrite == -1) {
perror("write");
exit(EXIT_FAILURE);
}
}
if (close(fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
return 0;
}
```
在上面的代码中,我们使用了 `open`、`read`、`write` 和 `close` 系统调用来完成文件的读写。首先,我们通过 `open` 打开指定文件,并根据传入的 `mode` 参数选择读或写模式。然后,如果是读模式,我们使用 `read` 从文件中读取数据,并将其输出到控制台;如果是写模式,我们使用 `write` 将指定的学号写入文件。最后,我们通过 `close` 关闭文件描述符。
注意,在使用 `read` 读取文件时,我们需要在读取到的数据末尾手动添加一个字符串结束符 `\0`,以便后续的字符串操作。
您可以通过以下命令编译和运行该程序:
```
$ gcc -o file_rw file_rw.c
$ ./file_rw myfile.txt O_WRONLY
```
其中,`myfile.txt` 是要读写的文件名,`O_WRONLY` 表示写模式。如果要读取文件,将 `O_WRONLY` 替换为 `O_RDONLY` 即可。
阅读全文