Linux C语言文件读写

这篇博客介绍了如何在Linux系统中使用C语言进行文件的读写操作。通过`open`函数以读写模式打开或创建文件"Linux.txt",接着使用`write`函数写入字符串"hello world!",然后关闭文件。之后再以只读模式重新打开文件,用`read`函数读取内容到缓冲区,并打印出来。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

void main(){
     int fd,size;
     char s[] = "hello world!" ,buffer[200];
     /*打开 /home/yyf/Desktop/Linux 做写入,如果该文件不存在则建立该文件*/
     /*参数O_WRONLY 以只写到方式打开文件*/
     /*参数O_CREAT  若欲打开到文件不存在,则建立该文件*/
     /*参数O_RDWR 以读写方式打开文件*/
     /*参数O_RDONLY 以只读方式打开文件*/
     fd = open("/home/yyf/Desktop/Linux.txt",O_RDWR|O_CREAT,00777);
     if(fd == -1)
          perror("fd");
     write(fd,s,strlen(s));
     close(fd);

 
     /*打开 /home/yyf/Desktop/Linux 做读取动作*/
     fd = open ("/home/yyf/Desktop/Linux.txt",O_RDONLY);
     size = read(fd,buffer,sizeof(buffer));
     if (size == -1)
          perror("read");
     close(fd);
     printf("%s\n",buffer);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值