C/C++从文本文件读取数据
2017-10-24 14:58
274 查看
本文主要是利用C函数fread、fwrite、fscanf以及C++文件流ifstream、ofstream等函数从文件读写。
1、测试读写结构体数组
2、按照指定格式从文本读取数据
3、C++文件流读写
#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++文件流读写
相关文章推荐
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组 (转)
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- 收集两个C++写的从文本文件中读取数据保存到数组的程序
- c++中读取文本文件单行数据的正确做法
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- 如何用C++读取文本文件中的数据存入到一个数组,并且对该数组任意长度求和
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组