C/C++从文本文件读取数据

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zhangfuliang123/article/details/78329665

    本文主要是利用C函数fread、fwrite、fscanf以及C++文件流ifstream、ofstream等函数从文件读写。

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <String>
using namespace std;
struct student
{
	int num;
	int age;
	char name[30];
	//使用char *name;读取结构体出错
};
//写入结构体数组
void writeStruct()
{
    student* listStruct;
	const int Size = 5;
	listStruct = (struct student*)malloc(sizeof(struct student) * Size);
	FILE *fp;
	for (int i = 0; i < Size; i++){
		listStruct[i].num = i;
		listStruct[i].age = i * 10;
		strcpy(listStruct[i].name, "name");
	}
	fp = fopen("test.txt", "wb");
	if (fp == NULL){
		printf("Open File failed.\n");
		exit(0);
	}
	for (int i = 0; i < Size; i++){
		if (fwrite(&listStruct[i], sizeof(struct student), 1, fp) != 1){
			printf("File Write Error.\n");
		}
	}
	printf("write data success.\n");
	fclose(fp);
}

//读取到结构体
void readStruct(){
	FILE * fp;
	if ((fp = fopen("test.txt", "rb")) == NULL){
		printf("Open File failed.\n");
		exit(0);
	}
	student one;
	printf("read data:\n");
	while (fread(&one, sizeof(struct student), 1, fp) == 1){
		printf("%d %d %s\n", one.num, one.age, one.name);
	}
	fclose(fp);
}


//按照指定格式从文本中读取多行数据
void readFile(){
	FILE *fp;
	fp = fopen("read.txt", "r");
	if (fp == NULL){
		printf("Open File failed.\n");
		exit(0);
	}
	int a;
	float c;
	char str[100];
	while (!feof(fp)){
		fscanf(fp, "%d%s%f", &a, &str, &c);
		printf("Line:%d %s %.1f\n", a, str, c);
	}
	fclose(fp);
}

//C++ 文件流读写
void writeStream(){
	ofstream out;
	out.open("11.txt", ios::trunc);
	if (!out.is_open()){
		cout << "open File Failed." << endl;
		return;
	}
	char a = 'a';
	for (int i = 0; i < 5; i++){
		out << i << "\t" << a << endl;
		a++;
	}
	out.close();
}

void readStream(){
	ifstream in;
	in.open("11.txt", ios::in);
	if (!in.is_open()){
		cout << "open File Failed." << endl;
		return;
	}
	string strOne;
	while (getline(in, strOne)){
		stringstream ss;
		ss << strOne;
		int a;
		char c;
		ss >> a >> c;
		cout << a <<"  "<< c << endl;
	}

}


int main(){
	writeStruct();
	readStruct();
	//readFile();
	//writeStream();
	//readStream();
	return 0;
}

1、测试读写结构体数组


2、按照指定格式从文本读取数据


3、C++文件流读写


展开阅读全文

没有更多推荐了,返回首页