c语言 open()文件 写入
时间: 2023-12-04 14:05:24 浏览: 37
在 C 语言中,要使用 open() 函数打开文件并进行写入操作,需要包含头文件 <fcntl.h> 和 <sys/types.h>。下面是一个简单的例子:
```c
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main()
{
int fd = open("example.txt", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
// 打开或创建名为 example.txt 的文件,设置权限为用户可读可写
if (fd == -1)
{
perror("open");
return 1;
}
char *str = "Hello, world!\n";
ssize_t ret = write(fd, str, strlen(str));
// 写入字符串到文件中
if (ret == -1)
{
perror("write");
close(fd);
return 1;
}
close(fd);
return 0;
}
```
在上面的代码中,我们首先使用 open() 函数打开或创建名为 example.txt 的文件,并设置了文件的访问权限。然后使用 write() 函数将字符串写入到文件中,最后使用 close() 函数关闭文件。如果在打开或写入文件时出现错误,可以使用 perror() 函数输出错误信息。