Linux cc++文件的基本 *** 作

Linux cc++文件的基本 *** 作,第1张

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置到文件末尾+偏移字节)

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5710718.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存