您的位置:首页 > 编程语言 > C语言/C++

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

2017-10-24 14:58 274 查看
本文主要是利用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++文件流读写

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐