使用C++中的Fortran格式迭代文本文件

Pas*_*ten 8 c++ parsing fortran text-parsing

我正在制作一个处理txt文件数据的应用程序.

这个想法是txt文件可能有不同的格式,应该读入C++.

一个例子可能是3I2, 3X, I3,应该这样做:"首先我们有3个长度为2的整数,然后我们有3个空点,然后我们有1个长度为3的整数.

是最好迭代文件,产生线,然后迭代线作为字符串?什么是一个有效的方法迭代巧妙地省略3个点被忽略?

例如

101112---100
102113---101
103114---102
Run Code Online (Sandbox Code Playgroud)

至:

10, 11, 12, 100
10, 21, 13, 101
10, 31, 14, 102
Run Code Online (Sandbox Code Playgroud)

Jon*_*rsi 8

Kyle Kanos给出的链接很好;*scanf/*printf格式字符串很好地映射到fortran格式字符串.使用C风格的IO实际上更容易实现,但使用C++样式流也是可行的:

#include <cstdio>
#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream fortranfile;
    fortranfile.open("input.txt");

    if (fortranfile.is_open()) {

        std::string line;
        getline(fortranfile, line);

        while (fortranfile.good()) {
            char dummy[4];
            int i1, i2, i3, i4;

            sscanf(line.c_str(), "%2d%2d%2d%3s%3d", &i1, &i2, &i3, dummy, &i4);

            std::cout << "Line: '" << line << "' -> " << i1 << " " << i2 << " "
                      << i3 << " " << i4 << std::endl;

            getline(fortranfile, line);
        }
    }

    fortranfile.close();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

跑步给

$ g++ -o readinput readinput.cc
$ ./readinput
Line: '101112---100' -> 10 11 12 100
Line: '102113---101' -> 10 21 13 101
Line: '103114---102' -> 10 31 14 102
Run Code Online (Sandbox Code Playgroud)

这里我们使用的格式字符串是%2d%2d%2d%3s%3d- 3个%2d(宽度为2的十进制整数)后跟%3s(宽度为3的字符串,我们读入一个我们从未使用过的变量)后跟%3d(宽度为3的十进制整数).


jrd*_*rd1 6

鉴于您希望动态解析Fortran格式说明符标志,您应该注意:您已经立即进入解析器领域.

除了解析其他人在此处注意到的输入的其他方法:

  • 通过使用Fortran和CC/++绑定为您进行解析.
  • 使用纯C++通过使用以下组合编写解析器来为您解析它:
    • sscanf
    • streams

我的建议是,如果你可以使用boost,你可以使用它来实现一个简单的解析器,用于动态操作,使用Regex和STL容器的组合.

根据您所描述的内容以及在不同位置显示的内容,您可以使用正则表达式捕获构建您希望支持的语法的简单实现:

(\\d{0,8})([[:alpha:]])(\\d{0,8})
Run Code Online (Sandbox Code Playgroud)
  1. 第一组是该变量类型的数量.
  2. 第二个是变量的类型.
  3. 第三个是变量类型的长度.

使用此Fortran Format Specifier Flags参考,您可以实现一个天真的解决方案,如下所示:

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <boost/regex.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

//A POD Data Structure used for storing Fortran Format Tokens into their relative forms
typedef struct FortranFormatSpecifier {
    char type;//the type of the variable
    size_t number;//the number of times the variable is repeated
    size_t length;//the length of the variable type
} FFlag;

//This class implements a rudimentary parser to parse Fortran Format
//Specifier Flags using Boost regexes.
class FormatParser {
public:
    //typedefs for further use with the class and class methods
    typedef boost::tokenizer<boost::char_separator<char> > bst_tokenizer;
    typedef std::vector<std::vector<std::string> > vvstr;
    typedef std::vector<std::string> vstr;
    typedef std::vector<std::vector<int> > vvint;
    typedef std::vector<int> vint;

    FormatParser();
    FormatParser(const std::string& fmt, const std::string& fname);

    void parse();
    void printIntData();
    void printCharData();

private:
    bool validateFmtString();
    size_t determineOccurence(const std::string& numStr);
    FFlag setFortranFmtArgs(const boost::smatch& matches);
    void parseAndStore(const std::string& line);
    void storeData();

    std::string mFmtStr;                //this holds the format string
    std::string mFilename;              //the name of the file

    FFlag mFmt;                         //a temporary FFlag variable
    std::vector<FFlag> mFortranVars;    //this holds all the flags and details of them
    std::vector<std::string> mRawData;  //this holds the raw tokens

    //this is where you will hold all the types of data you wish to support
    vvint mIntData;                     //this holds all the int data
    vvstr mCharData;                    //this holds all the character data (stored as strings for convenience)
};

FormatParser::FormatParser() : mFmtStr(), mFilename(), mFmt(), mFortranVars(), mRawData(), mIntData(), mCharData() {}
FormatParser::FormatParser(const std::string& fmt, const std::string& fname) : mFmtStr(fmt), mFilename(fname), mFmt(), mFortranVars(), mRawData(), mIntData(), mCharData() {}

//this function determines the number of times that a variable occurs
//by parsing a numeric string and returning the associated output
//based on the grammar
size_t FormatParser::determineOccurence(const std::string& numStr) {
    size_t num = 0;
    //this case means that no number was supplied in front of the type
    if (numStr.empty()) {
        num = 1;//hence, the default is 1
    }
    else {
        //attempt to parse the numeric string and find it's equivalent
        //integer value (since all occurences are whole numbers)
        size_t n = atoi(numStr.c_str());

        //this case covers if the numeric string is expicitly 0
        //hence, logically, it doesn't occur, set the value accordingly
        if (n == 0) {
            num = 0;
        }
        else {
            //set the value to its converted representation
            num = n;
        }
    }
    return num;
}

//from the boost::smatches, determine the set flags, store them
//and return it
FFlag FormatParser::setFortranFmtArgs(const boost::smatch& matches) {
    FFlag ffs = {0};

    std::string fmt_number, fmt_type, fmt_length;

    fmt_number = matches[1];
    fmt_type = matches[2];
    fmt_length = matches[3];

    ffs.type = fmt_type.c_str()[0];

    ffs.number = determineOccurence(fmt_number);
    ffs.length = determineOccurence(fmt_length);

    return ffs;
}

//since the format string is CSV, split the string into tokens
//and then, validate the tokens by attempting to match them
//to the grammar (implemented as a simple regex). If the number of
//validations match, everything went well: return true. Otherwise:
//return false.
bool FormatParser::validateFmtString() {    
    boost::char_separator<char> sep(",");
    bst_tokenizer tokens(mFmtStr, sep);
    mFmt = FFlag();

    size_t n_tokens = 0;
    std::string token;

    for(bst_tokenizer::const_iterator it = tokens.begin(); it != tokens.end(); ++it) {
        token = *it;
        boost::trim(token);

        //this "grammar" is based on the Fortran Format Flag Specification
        std::string rgx = "(\\d{0,8})([[:alpha:]])(\\d{0,8})";
        boost::regex re(rgx);
        boost::smatch matches;

        if (boost::regex_match(token, matches, re, boost::match_extra)) {
            mFmt = setFortranFmtArgs(matches);
            mFortranVars.push_back(mFmt);
        }
        ++n_tokens;
    }

    return mFortranVars.size() != n_tokens ? false : true;
}

//Now, parse each input line from a file and try to parse and store
//those variables into their associated containers.
void FormatParser::parseAndStore(const std::string& line) {
    int offset = 0;
    int integer = 0;
    std::string varData;
    std::vector<int> intData;
    std::vector<std::string> charData;

    offset = 0;

    for (std::vector<FFlag>::const_iterator begin = mFortranVars.begin(); begin != mFortranVars.end(); ++begin) {
        mFmt = *begin;

        for (size_t i = 0; i < mFmt.number; offset += mFmt.length, ++i) {
            varData = line.substr(offset, mFmt.length);

            //now store the data, based on type:
            switch(mFmt.type) {
                case 'X':
                  break;

                case 'A':
                  charData.push_back(varData);
                  break;

                case 'I':
                  integer = atoi(varData.c_str());
                  intData.push_back(integer);
                  break;

                default:
                  std::cerr << "Invalid type!\n";
            }
        }
    }
    mIntData.push_back(intData);
    mCharData.push_back(charData);
}

//Open the input file, and attempt to parse the input file line-by-line.
void FormatParser::storeData() {
    mFmt = FFlag();
    std::ifstream ifile(mFilename.c_str(), std::ios::in);
    std::string line;

    if (ifile.is_open()) {
        while(std::getline(ifile, line)) {
            parseAndStore(line);
        }
    }
    else {
        std::cerr << "Error opening input file!\n";
        exit(3);
    }
}

//If character flags are set, this function will print the character data
//found, line-by-line
void FormatParser::printCharData() {    
    vvstr::const_iterator it = mCharData.begin();
    vstr::const_iterator jt;
    size_t linenum = 1;

    std::cout << "\nCHARACTER DATA:\n";

    for (; it != mCharData.end(); ++it) {
        std::cout << "LINE " << linenum << " : ";
        for (jt = it->begin(); jt != it->end(); ++jt) {
            std::cout << *jt << " ";
        }
        ++linenum;
        std::cout << "\n";
    }
}

//If integer flags are set, this function will print all the integer data
//found, line-by-line
void FormatParser::printIntData() {
    vvint::const_iterator it = mIntData.begin();
    vint::const_iterator jt;
    size_t linenum = 1;

    std::cout << "\nINT DATA:\n";

    for (; it != mIntData.end(); ++it) {
        std::cout << "LINE " << linenum << " : ";
        for (jt = it->begin(); jt != it->end(); ++jt) {
            std::cout << *jt << " ";
        }
        ++linenum;
        std::cout << "\n";
    }
}

//Attempt to parse the input file, by first validating the format string
//and then, storing the data accordingly
void FormatParser::parse() {
    if (!validateFmtString()) {
        std::cerr << "Error parsing the input format string!\n";
        exit(2);
    }
    else {
        storeData();
    }
}

int main(int argc, char **argv) {
    if (argc < 3 || argc > 3) {
        std::cerr << "Usage: " << argv[0] << "\t<Fortran Format Specifier(s)>\t<Filename>\n";
        exit(1);
    }
    else {
        //parse and print stuff here
        FormatParser parser(argv[1], argv[2]);
        parser.parse();

        //print the data parsed (if any)
        parser.printIntData();
        parser.printCharData();
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是标准的c ++ 98代码,可以编译如下:

g++ -Wall -std=c++98 -pedantic fortran_format_parser.cpp -lboost_regex
Run Code Online (Sandbox Code Playgroud)

奖金

这个基本的解析器也可以工作Characters(Fortran格式标志'A',​​最多8个字符).您可以通过编辑正则表达式并对类型一起检查捕获的字符串的长度来扩展它以支持您可能喜欢的任何标志.

可能的改进

如果您可以使用C++ 11,则可以lambdas在某些地方使用并替换auto迭代器.

如果这是在有限的内存空间中运行,并且您必须解析一个大文件,那么由于vectors内部管理内存的方式,向量将不可避免地崩溃.最好使用它deques.有关详细信息,请参阅此处讨论的内容:

http://www.gotw.ca/gotw/054.htm

并且,如果输入文件很大,并且文件I/O是瓶颈,则可以通过修改ifstream缓冲区的大小来提高性能:

如何让IOStream表现更好?

讨论

您将注意到:您要解析的类型必须在运行时已知,并且类声明和定义中必须支持任何关联的存储容器.

正如您想象的那样,支持一个主类中的所有类型效率不高.但是,由于这是一个天真的解决方案,改进的完整解决方案可以专门用于支持这些情况.

另一个建议是使用Boost :: Spirit.但是,由于Spirit使用了大量模板,因此在发生错误时,调试此类应用程序并不适合胆小者.

性能

@Jonathan Dursi的解决方案相比,这个解决方案很慢:

对于使用相同行格式("3I2,3X,I3")的10,000,000行随机生成的输出(124MiB文件):

#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main(int argc, char **argv) {
    srand(time(NULL));
    if (argc < 2 || argc > 2) {
        printf("Invalid usage! Use as follows:\t<Program>\t<Output Filename>\n");
        exit(1);
    }

    ofstream ofile(argv[1], ios::out);
    if (ofile.is_open()) {
        for (int i = 0; i < 10000000; ++i) {
             ofile << (rand() % (99-10+1) + 10) << (rand() % (99-10+1) + 10) << (rand() % (99-10+1)+10) << "---" << (rand() % (999-100+1) + 100) << endl;
        }
    }

    ofile.close();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的解决方案

0m13.082s
0m13.107s
0m12.793s
0m12.851s
0m12.801s
0m12.968s
0m12.952s
0m12.886s
0m13.138s
0m12.882s
Run Code Online (Sandbox Code Playgroud)

时钟的平均壁挂时间为 12.946s

Jonathan Dursi的解决方案:

0m4.698s
0m4.650s
0m4.690s
0m4.675s
0m4.682s
0m4.681s
0m4.698s
0m4.675s
0m4.695s
0m4.696s
Run Code Online (Sandbox Code Playgroud)

平均停电时间为 4.684s

在O2上,他比我的快至少270%.

但是,由于每次要解析其他格式标志时都不必实际修改源代码,因此此解决方案更加优化.

注意: 您可以实现一个解决方案,该解决方案涉及sscanf/ streams只需要您知道您希望读取的变量类型(非常类似于我的),但是额外的检查(例如验证类型)会增加开发时间.(这就是我在Boost中提供我的解决方案的原因,因为令牌化器和正则表达式的便利性 - 这使得开发过程更容易).

参考

http://www.boost.org/doc/libs/1_34_1/libs/regex/doc/character_class_names.html


hiv*_*ert 5

您可以翻译3I2, 3X, I3为scanf格式.


Joh*_*nck 5

鉴于Fortran可以很容易地从C调用,你可以编写一个Fortran函数来"本地"执行此操作.毕竟,Fortran READ函数采用您描述的格式字符串.

如果你想要这个,你需要在Fortran上刷一点点(http://docs.oracle.com/cd/E19957-01/806-3593/2_io.html),另外学习如何使用编译器链接Fortran和C++.以下是一些提示:

  • Fortran符号可能隐含地带有下划线,因此可以从C调用MYFUNC作为myfunc_().
  • 多维数组具有相反的维度顺序.
  • 在C++头中声明Fortran(或C)函数需要将其放在extern "C" {}作用域中.

  • 如果您决定通过调用Fortran获取Fortran IO,我建议使用Fortran的ISO_C_Binding.这标准化了C(和C++通过extern C)和Fortran之间的接口 - 不用担心下划线! (4认同)