文件操作 有关系统调用 写文件的相关程序
write.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define SIZE 1024
int main()
{
int fd = open("abc", O_WRONLY|O_CREAT, 0777);
if (fd == -1)
{
perror ("open");
return -1;
}
char buf[SIZE] = {0};
while (1)
{
fgets (buf, SIZE, stdin);
if (strncmp ("end", buf, 3) == 0)
break;
ssize_t ret = write(fd, buf, strlen(buf));
if (ret == -1)
{
perror ("write");
}
printf ("要写的字节数 :%d, 实际写的字节数: %d\n", SIZE, ret);
}
close(fd);
return 0;
}
本文提供了一个使用C语言进行文件写入操作的示例程序。该程序通过系统调用打开一个名为“abc”的文件,并从标准输入读取数据直至遇到end字符串为止,然后将读取的内容写入文件。程序展示了如何使用open、write和close等函数来完成基本的文件I/O操作。
4237

被折叠的 条评论
为什么被折叠?



