使用系统调用open read write,完成一个C语言程序:该程序接收两个参数,参数1作为要读写的文件,参数2作为标志位,标识是读还是写。功能完成对参数1所示文件的读写,该文件的内容为 “学号 MYFILE”,其中学号填为自己的学号。
时间: 2024-03-26 22:35:08 浏览: 52
以下是一个使用系统调用`open`、`read`和`write`来完成文件读写的C语言程序,可以实现您的需求:
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define MAX_BUF_SIZE 1024
int main(int argc, char *argv[]) {
char *filename = argv[1]; // 获取要读写的文件名
int flag = atoi(argv[2]); // 获取标志位,0为读,1为写
int fd = open(filename, flag == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0644); // 打开文件
if (fd == -1) {
perror("open");
exit(1);
}
char buf[MAX_BUF_SIZE];
memset(buf, 0, MAX_BUF_SIZE);
if (flag == 0) { // 读取文件内容
if (read(fd, buf, MAX_BUF_SIZE) == -1) {
perror("read");
exit(1);
}
printf("读取文件内容:%s\n", buf);
} else { // 写入文件内容
sprintf(buf, "学号 %s", "MYFILE"); // 将学号填写到缓冲区中
if (write(fd, buf, strlen(buf)) == -1) {
perror("write");
exit(1);
}
printf("写入文件成功!\n");
}
close(fd); // 关闭文件
return 0;
}
```
您可以将上面的代码保存到一个名为`file_rw.c`的文件中,然后使用以下命令进行编译:
```
gcc -o file_rw file_rw.c
```
编译成功后,您可以使用以下命令来运行程序并进行文件读写:
```
./file_rw file.txt 1
```
其中,`file.txt`为您要读写的文件名,`1`表示进行写操作。如果您想进行读操作,可以将最后一个参数改为`0`。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)