栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Linux c/c++文件的基本操作

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Linux c/c++文件的基本操作

Linux c/c++文件的基本操作

文件的创建以及写入数据

#include 
#include 
#include 

typedef struct student{
	int id;
	char name[20];
	int age;
	float score;
}STU;

int main(){
	//以只写的方式打开文件,如果文件不存在就创建文件
	int fd = open("1.txt",O_WRONLY);
	if(-1 == fd){   //文件打开失败
		perror("文件打开失败!n");
		fd = open("1.txt",O_CREAT | O_WRONLY,0666);
		if(-1 == fd){
			printf("文件创建失败!n");
		}else{
			printf("文件创建成功!n");
		}
	}else{        //文件打开成功
		printf("文件打开成功!n");
	}
	//向文件之中写入内容
	STU stu[5]={
		{1001,"张飞",40,50},
		{1002,"刘备",30,40},
		{1003,"关羽",52,60},
		{1004,"孙尚香",20,100},
		{1005,"貂蝉",18,70}
	};
	//write(fd,stu,sizeof(STU)*5);
	for (int i = 0; i < 5; ++i)
	{
		write(fd,&stu[i],sizeof(STU));
	}

	//关闭文件
	close(fd);
	return 0;
}

文件的打开以及读取数据

#include 
#include    //exit()
#include     //open()
#include    //close()

typedef struct student{
	int id;
	char name[20];
	int age;
	float score;
}STU;

int main(){
	//以只读的方式打开文件
	int fd = open("1.txt",O_RDONLY);
	if(-1 == fd){
		printf("文件打开失败!%mn"),exit(-1);
	}else{
		printf("文件打开成功!n");
	}
	STU stu;
	for (int i = 0; i < 5; ++i)
	{
		read(fd,&stu,sizeof(STU));
		printf("id:%d,name:%s,age:%d,score:%gn",
			stu.id,stu.name,stu.age,stu.score);
	}

	//关闭文件
	close(fd);
	return 0;
}

文件描述符fd的位置重置

#include 
#include 
#include  //close()
#include  //exit()

//lseek()重置fd(文件描述符)位置函数
//每隔两个个字符读取一个字母
int main(){
	//打开文件,如果打开失败就创建
	int fd = open("2.txt",O_RDONLY);
	if(-1 == fd){
		printf("文件打开失败:%m"),exit(-1);
	}
	printf("文件打开成功!n");

	char c;
	int r;
	while(1){
		r = read(fd,&c,sizeof(char));
		if(r>0){                 //有内容
			printf("%cn",c);
		}else{
			break;
		}
		lseek(fd,2,SEEK_CUR);
	}

	//关闭文件
	close(fd);
	return 0;
}

    open()函数
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
//参数1: 文件路径 + 文件名字
//参数2: 文件打开方式或创建方式
//参数3: 文件权限(通常使用三位八进制代替0666表示u g o 均为wr权限)
    write()函数
ssize_t write(int fd, const void *buf, size_t count);
//参数1: 文件描述符fd
//参数2: 写入的内容的地址
//参数3: 写入内容的大小
    read()函数
ssize_t read(int fd, void *buf, size_t count);
//参数1: 文件描述符fd
//参数2: 读取使用的缓冲内存地址
//参数3: 读取的大小
    close()函数
int close(int fd);
//参数1: 文件描述符fd
    lseek()函数
off_t lseek(int fd, off_t offset, int whence);
//参数1: 文件描述符fd
//参数2: 偏移大小
//参数3: 偏移的位置
SEEK_SET 偏移量设置为偏移字节(fd置到偏移文件开头+偏移字节)
SEEK_CUR 偏移量设置为当前位置加偏移字节(fd置到当前位置+偏移字节)
SEEK_END 偏移量设置为文件大小加偏移字节(fd置到文件末尾+偏移字节)

如有错误,还请大佬们指正,嘻嘻嘻!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/714069.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号