簡體   English   中英

在C ++中讀取txt文件

[英]read in txt file in C++

我有一個.txt參數文件,如下所示:

#Stage
filename = "a.txt";
...

#Stage
filename = "b.txt";
...

基本上,每次訪問參數文件時,我都希望閱讀一個階段。 我計划在帶有分隔符“ #Stage”的C ++中使用getline來執行此操作。 還是有更好的方法來解決這個問題? 任何示例代碼都將有所幫助。

*struct content{
    DATA data;
    content* next;
};
struct List{
    content * head;
};

static List * list;
char buf[100];
FILE * f = fopen(filename);
while(NULL != fgets(buf,f))
{
    char str[100] ={0};
    sccanf(buf,"%s",str);
    if(strcmp("#Stage",str) == 0)
    {
        // read content and add to list
        cnntent * p = new content();
        list->add();

    }
    else
    {
        //update content in last node
        list->last().data = 
    }
}*

也許我應該表達得更加清楚。 無論如何,我這樣管理:

ifstream file1;
file1.open(parfile, ios::binary);
if (!file1) {
    cout<<"Error opening file"<<parfile<<"for read"<<endl;
    exit(1);
}

std::istreambuf_iterator<char> eos;
std::string s(std::istreambuf_iterator<char>(file1), eos);

unsigned int block_begin = 0;
unsigned int block_end = string::npos;

for (unsigned int i=0; i<stage; i++) {

    if(s.find("#STAGE", block_begin)!=string::npos) {
    block_begin = s.find("#STAGE", block_begin);
    }
}

if(s.find("#STAGE", block_begin)!=string::npos) {
block_end = s.find("#STAGE", block_begin);
}


string block = s.substr(block_begin, block_end);

stringstream ss(block);
....

我會逐行閱讀,忽略行,以# (或行,內容為#Stage ,取決於格式/目標) #Stage (因為沒有getline版本,以std::string為分隔符)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM