首页 > 系统服务 > 详细

Linux文件读写笔记

时间:2019-11-09 18:07:37      阅读:104      评论:0      收藏:0      [点我收藏+]

读文件:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //linux下面的头文件
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main(int avg, char* avgs[])
{
	if (avg < 2)
	{
		printf("参数错误\n");
		return EXIT_FAILURE;
	}
	char s[] = "abc.txt";
	int fd = open(avgs[1], O_RDONLY);
	if (fd == -1)
	{
		printf("error :%s\n", strerror(errno));
	}
	else
	{
		printf("fd=%d\n", fd);
		char buf[100];
		memset(buf, 0, sizeof(buf));
		//循环读取文件
		while (read(fd, buf, sizeof(buf)-1)>0)
		{
			printf("buf:%s\n", buf);
			memset(buf, 0, sizeof(buf));
		}
		close(fd);
	}
	return 0;
}

  

写文件:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //linux下面的头文件
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main(int avg, char* avgs[])
{
	if (avg < 2)
	{
		printf("参数错误\n");
		return EXIT_FAILURE;
	}
	int fd = open(avgs[1], O_RDWR | O_APPEND);
	if (fd==-1)
	{
		printf("file open error : %s \n", strerror(errno));
		return EXIT_FAILURE;
	}
	else
	{
		printf("fd= %d\n", fd);
		char buf[100];
		memset(buf, 0, sizeof(buf));
		strcpy(buf, "RtesttesttestR");
		int i = write(fd, buf, strlen(buf));
		close(fd);
	}
	return 0;
}

  

 

 

 

技术分享图片

 

Linux文件读写笔记

原文:https://www.cnblogs.com/caoruipeng/p/11826817.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!