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

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

文件的创建以及写入数据

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

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 <stdio.h>
#include <stdlib.h>   //exit()
#include <fcntl.h>    //open()
#include <unistd.h>   //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("文件打开失败!%m\n"),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:%g\n",
			stu.id,stu.name,stu.age,stu.score);
	}

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

在这里插入图片描述

文件描述符fd的位置重置

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h> //close()
#include <stdlib.h> //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("%c\n",c);
		}else{
			break;
		}
		lseek(fd,2,SEEK_CUR);
	}

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

在这里插入图片描述

  1. 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权限)
  1. write()函数
ssize_t write(int fd, const void *buf, size_t count);
//参数1: 文件描述符fd
//参数2: 写入的内容的地址
//参数3: 写入内容的大小
  1. read()函数
ssize_t read(int fd, void *buf, size_t count);
//参数1: 文件描述符fd
//参数2: 读取使用的缓冲内存地址
//参数3: 读取的大小
  1. close()函数
int close(int fd);
//参数1: 文件描述符fd
  1. lseek()函数
off_t lseek(int fd, off_t offset, int whence);
//参数1: 文件描述符fd
//参数2: 偏移大小
//参数3: 偏移的位置
SEEK_SET 偏移量设置为偏移字节(fd置到偏移文件开头+偏移字节)
SEEK_CUR 偏移量设置为当前位置加偏移字节(fd置到当前位置+偏移字节)
SEEK_END 偏移量设置为文件大小加偏移字节(fd置到文件末尾+偏移字节)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

石小浪♪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值