首页 > 解决方案 > C++ 数据资源文件

问题描述

抱歉,如果这是一个奇怪或简单的问题。但最近我和一位潜在的老雇主之间的电子邮件交流中出现了数据资源文件的话题。我没有直接评论他何时使用“数据资源文件”一词或他阅读文件的要求,因为我对它们了解不多。

我在谷歌上搜索什么是数据资源文件和一些在线信息,链接表明它们可以是具有几个不同扩展名的多种文件类型。值得一提的是,我是一名 C++ 程序员,所以给出的任何代码示例都符合我熟悉的语言。

主要问题是如何从资源数据文件中读取 C++ 中的数据?(假设它不是一个普通的文本文件,因为我已经做了很多工作)

如果这是一件简单的事情并且我没有打开正确的谷歌资源,我再次道歉。

标签: fileresources

解决方案


1 个

此数据类型表示输出文件流,用于创建文件并将信息写入文件。

2

此数据类型表示输入文件流,用于从文件中读取信息。

3

这种数据类型一般代表文件流,同时具有ofstream和ifstream的能力,即可以创建文件,向文件写入信息,从文件中读取信息。

打开文件 必须先打开文件,然后才能对其进行读取或写入。ofstream 或 fstream 对象都可用于打开文件进行写入。ifstream 对象仅用于打开文件以供读取。

以下是 open() 函数的标准语法,它是 fstream、ifstream 和 ofstream 对象的成员。

void open(const char *filename, ios::openmode 模式); 这里,第一个参数指定要打开的文件的名称和位置,而 open() 成员函数的第二个参数定义应该打开文件的模式。

Sr.No 模式标志和描述 1
ios::app

追加模式。该文件的所有输出都将附加到末尾。

2
ios::吃

打开一个文件进行输出并将读/写控件移动到文件末尾。

3
ios::in

打开一个文件进行阅读。

4
ios::out

打开一个文件进行写入。

5
ios::trunc

如果文件已存在,则在打开文件之前将截断其内容。

读写示例

以下是以读写模式打开文件的 C++ 程序。将用户输入的信息写入名为 afile.dat 的文件后,程序从文件中读取信息并将其输出到屏幕上 -</p>

#include <fstream>
#include <iostream>
using namespace std;
 
int main () {
   char data[100];

   // open a file in write mode.
   ofstream outfile;
   outfile.open("afile.dat");

   cout << "Writing to the file" << endl;
   cout << "Enter your name: "; 
   cin.getline(data, 100);

   // write inputted data into the file.
   outfile << data << endl;

   cout << "Enter your age: "; 
   cin >> data;
   cin.ignore();
   
   // again write inputted data into the file.
   outfile << data << endl;

   // close the opened file.
   outfile.close();

   // open a file in read mode.
   ifstream infile; 
   infile.open("afile.dat"); 
 
   cout << "Reading from the file" << endl; 
   infile >> data; 

   // write the data at the screen.
   cout << data << endl;
   
   // again read the data from the file and display it.
   infile >> data; 
   cout << data << endl; 

   // close the opened file.
   infile.close();

   return 0;
}

是的,看起来很简单。但没有其他选择。具有自己扩展名的文件的读取方式相同。但是用一定的反序列化算法


推荐阅读