Linux 编程之文件操作

本用例简单联系Linux 下文件操作测试,基本过程是:

运行程序打开指定文件;

将buf_write数据写进文件;

将文件数据读取到buf_read; 

最后打印出读取到文件。

//read.c

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

#define BUF_SIZE 1024

int main(int argc,char*argv[])
{
	int fd;
	char buf_read[BUF_SIZE];
	char buf_write[]="hello world!";
	if(argc!=2)
	{
	
		printf("please input %s file name\n",argv[0]);
		return 0;
	}
	unlink(argv[1]);
	fd=open(argv[1],O_RDWR|O_CREAT|O_EXCL,S_IRWXU);//打开文件
	if(-1==fd)//打开失败则返回-1
	{
		perror("open");
		return -1;
	
	}
	
	int num_write=write(fd,buf_write,strlen(buf_write));//将buf_write 内容写进fd指向文件
	printf("num_write=%d\n",num_write);
	if(-1==num_write)
	{
		
		perror("write");
		return -1;
	}
	lseek(fd,0,SEEK_SET);//z在写操作后fd 文件描述符指向文件末尾,需要移动指向开头,否则接下来读出无数据。
	
	//system("echo you test >>1.txt");
	int num_read=read(fd,buf_read,sizeof(buf_read));//从fd指向文件读取内容到buf_read.
		if(-1==num_read)
		{
			perror("read");
			return -1;
		}
		buf_read[num_read]='\0';//读取字符后面添加字符串结束字符'\0'
		printf("read %d from %s to buf\n",num_read,argv[1]);
		printf("the buf is: %s\n",buf_read);
		
		close(fd);
	

	return 0;
}

最后运行效果:

zdg@ubuntu:/mnt/hgfs/SHARE/3.文件系统$ ./a.out  1.txt
num_write=12
read 12 from 1.txt to buf
the buf is: hello world!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值