Linux的文件I/O操作,首先,创建文件test.c;然后使用open()函数打开文件/home/guestuser1/work/file2;接着使用write()函数在文件中写入数据“Hello”;最后使用read()函数将数据读取。
时间: 2024-01-16 08:02:40 浏览: 25
好的,下面是Linux文件I/O操作的示例代码,你可以在终端中运行:
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
char buf[1024];
int fd, sz;
// 创建文件test.c
fd = creat("test.c", 0644);
if (fd < 0) {
perror("creat error");
exit(1);
}
// 打开文件/home/guestuser1/work/file2
fd = open("/home/guestuser1/work/file2", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) {
perror("open error");
exit(1);
}
// 在文件中写入数据"Hello"
sz = write(fd, "Hello", 5);
if (sz < 0) {
perror("write error");
exit(1);
}
// 关闭文件
close(fd);
// 重新打开文件,准备读取数据
fd = open("/home/guestuser1/work/file2", O_RDONLY);
if (fd < 0) {
perror("open error");
exit(1);
}
// 读取数据
sz = read(fd, buf, sizeof(buf));
if (sz < 0) {
perror("read error");
exit(1);
}
// 输出读取的数据
printf("Read string from file: %s\n", buf);
// 关闭文件
close(fd);
return 0;
}
```
运行后,会在当前目录下创建test.c文件,并在/home/guestuser1/work/file2文件中写入"Hello",然后再从文件中读取数据并输出。注意要使用root用户或者有足够权限的用户才能在/home/guestuser1/work/目录下创建和访问文件。