C/C++从文本文件读取数据
来源:互联网 发布:使命召唤ol优化差 编辑:程序博客网 时间:2024/05/21 11:16
本文主要是利用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++文件流读写
阅读全文
0 0
- C/C++从文本文件读取数据
- C语言:从文本文件中读取输入数据
- C/C++逐行读取文本文件的数据
- C语言:从文本文件中读取输入数据(升级版)
- objective-c 读取文本文件
- C#_StreamReader读取文本文件
- 从文本文件中读取数据
- 从文本文件中读取数据
- C语言从文本文件中用字符串读取一行数据,然后再依次遍历字符串将字符串中数据分配。
- 用c语言读取文本文件
- 用C语言读取文本文件
- [C#] 从数据库读取数据并输出
- 从文本文件中读取数据画图
- 从文本文件读取数据存储到数据库
- C++实现逐行从文本文件读取数据
- 改进版的从文本文件读取数据
- 以行为单位读取文本文件(c++)
- C++:文本文件的读取和输入
- 不记得在哪看到的一篇文章。蛮好的,如果作者看到了联系我,我好写明引用地址,原作者
- 【sdk驱动开发4】ps侧dma使用
- 安装Eclipse出现“The Eclipse executable launcher was unable to locate its companion shared library”错误
- 鼠标经过特效
- 结构体:struct 和 typedef struct应该以及结构体的构造函数 区别
- C/C++从文本文件读取数据
- PullToRefreshScrollView的使用 +Banner
- MONGODB学习之一
- SpringBoot非官方教程 | 终章:文章汇总
- jmeter 元件的作用域与执行顺序
- 闭包作用域问题
- MindManager 2018新视图洋葱图介绍
- R12 FA中“摊销“(Amortize Adjustment)的实际应用
- Hadoop学习笔记1