文件基本操作,输入输出

C语言

//C语言文件操作函数总览
#include<stdio.h> //头文件

File* fopen(const char* filename, const char* mode); //打开文件
//"wb"——文件每次都覆盖,打开文件的时候会先清空原来的内容;"ab"——文件末尾追加写入,不清空原来的内容
//在"wb"模式下,fopen返回值为NULL原因:1、文件不存在,2、文件是只读文件

int fclose(File* p); //关闭文件

size_t fwrite(const void* buf, size_t size, size_t count, File* p); //写入数据,buf即要写入的数据,size==1, 函数的返回值为字节数

size_t fread(void* buf, size_t size, size_t nelem, FILE* fp); //从文件中读取数据,size==1,nelem表示最多读取的字节数,函数的返回值为实际读取到的字节数
//文件写入,写入数字
int buf[4] = {Ox111, Ox222, Ox333, Ox444};
fwrite(buf, 1, sizeof(buf), fp); //直接按字节写入
for(int i = 0; i < 4; i++) //格式化为字符串写入
{
	char text[16];
	sprintf(text, "%d", buf[i]);
	fwrite(text, 1, strlen(text), fp);
}

double a = 4 / 3.0;
fwrite(&a, 1, sizeof(a), fp); //直接写入
char text[16];
sprintf(text, "%.2lf", a);
fwrite(text, 1, strlen(text), fp); //格式化为字符串后写入,会丢失数据
//文件写入,写入字符串
char buf[16] = "hello";
fwrite(buf, 1, sizeof(buf), fp);
//文件写入,写入结构体
struct Student
{
	int id;
	char gender;
	char name[16];
};
Student Xu = {1, 'M', "Xu"};

fwrite(&Xu, 1, sizeof(Xu), fp); //整体写入
fwrite(&Xu.id, 1, 4, fp); //分别写入
fwrite(&Xu.gender, 1, 1, fp);
fwrite(&Xu.name, 1, 16, fp);
//文件读取
const char* filename = "";
FILE* fp = fopen(filename, "rb");
if(fp == NULL) //返回值为NULL可能是目标文件不存在或者fopen()参数设置错误,必须要设置为"rb"
{
	//...
}
char buf[128];
int n = fread(buf, 1, 128, fp);

//顺序读取(从头开始读取,顺序读取,已经读取的内容无法回头重新读取)
char buf[4]; //每次只读四个字节
while(!feof(fp))
{
	int n = fread(buf, 1, 4, fp);
	//...
}

C++

//写入到文本文件中
#include<iostream>
#include<fstream>

ofstream outFile;
outFile.open("output.txt");
outFile << "123" << endl;
outFile.close();
//读取文本文件
#include<iostream>
#include<fstream>

ifstream inFile;
inFile.open("input.txt");
if(!inFile.is_open())
{
	exit(EXIT_FAILURE);
}
double value; //用于存放读取到的数据
while(inFile.good())
{
	inFile >> value;
	char line[50];
	inFile.getline(line, 50); //读取一整行数据
	//数据操作等
}
if(inFile.eof())
	cout << "End of file.\n" << endl;
else if(inFile.fail())
	cout << "Input terminated by data mismatch.\n" << endl;
else
	cout << "Input terminated by unknown reason.\n" << endl;
inFile.close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值