使用 fstream 对象将文件中的信息存储到变量中

using fstream object to store information from a file into variables

本文关键字:信息 存储 变量 使用 对象 文件 fstream      更新时间:2023-10-16

我有以下代码块,用于读取以下格式的文本文件:

firstname lastname id mark
firstname lastname id mark

以下是代码块。

void DBManager::ReadFile(void){
fstream myfile; /*fstream object that will be used for file input and output operations*/
char* fn;       /*pointer to the storage which will hold firstname*/
char* ln;       /*pointer to the storage which will hold lastname*/
int id;         /*integer var to hold the id*/
float mark;     /*float var to hold the mark*/
/*read in the filename*/
g_FileName = new char[1024];                /*allocate memory on the heap to store filename*/
cout << "Please enter the filename:";
    cin >> g_FileName;
/*open file*/
myfile.open(g_FileName, ios::in | ios::out);
if(myfile.is_open()){   /*check if the file opening is successful*/
    cout << "File reading successful !n";
    /*read information from the file into temporary variables before passing them onto the heap*/
    while (!myfile.eof()) {
        fn=(char*) new char[1024];
        ln=(char*) new char[1024];
        myfile >> fn >> ln >> id >> mark;
        cout << fn << " " << ln << " " << id << " " << mark << " " << endl;
    }
    myfile.close();
}
else{                   /*else print error and return*/
    perror("");
    return;
}

}

上面的代码块有效! :)但是我很惊讶myfile如何知道它应该一次保持一行,以及它在设置四个变量方面足够聪明。

我是C++新手,因此这可能会在某种文档中涵盖。但是我很乐意从您那里获得一些见解,或者链接到我可以更好地理解 fstream 对象的地方。

在C++中,std::fstream是一种专门用于文件的流。从文件读取时,std::fstream的界面几乎与std::cin相同。输入流被编程为在>>运算符询问时读取下一个单词或数字。他们知道单词和数字在哪里,因为它们被空格隔开。在默认区域设置中,空格、制表符和换行符被视为空格。您可以更改区域设置以包含其他字符(如逗号),并在读取文件时跳过这些字符。基本上,当使用输入流读取时,换行符和空格的处理方式相同。

这里有一些关于学习流的很好的解释:http://www.cprogramming.com/tutorial/c++-iostreams.html

我不确定问题是什么。但是,代码存在几个问题:

  1. 您应该在尝试阅读始终检查输入。
  2. 测试eof()以确定是否有更多内容要阅读不起作用。
  3. 您有一个内存泄漏,在每个迭代器中分配内存。
  4. 在没有约束的情况下读取char数组是不安全的,即它容易被缓冲区覆盖(主要的攻击媒介之一)。

你想使用如下所示的循环:

std::string fn, ln;
while (myfile >> fn >> ln >> id >> mark) {
     ...
}