C ++重写一个文件,但在一个单词之前省略一切 [英] C++ Rewrite a file but leaving out everything before a word

查看:229
本文介绍了C ++重写一个文件,但在一个单词之前省略一切的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Visual C ++ Express 2010 ...我对C ++非常新。

I'm using Visual C++ Express 2010... and I'm very new to C++.

我想读取一个文件,

这是我到目前为止阅读文件的代码:

Here's the code I've got for reading the file so far:

#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;

int main() {
  ifstream myReadFile;
  myReadFile.open("text.txt");
  char output[500];
  int found;
  int line;
  if (myReadFile.is_open()) {
    line = 0;
 while (!myReadFile.eof()) {
     myReadFile >> output;
     if(line > 20) {
         cout << output;
     }
     line++;
 }
}
myReadFile.close();
system("PAUSE");
return 0;
}

提前非常感谢。

推荐答案

您不能读取文件,然后删除单词< - 开始 - >之前的所有内容,并将其重写为除了本杰明回答的记忆。否则,你需要一个中间文件。在所有情况下,您应该处理各种错误条件。这应该:

You cannot read a file then remove everything before the word "<--START-->" and rewrite the file with the rest, except in memory as answered by Benjamin. Otherwise you need an intermediate file. In all cases you should handle various error conditions. This should do it:

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

using namespace std;

int main() 
{   
    if (rename("Text.txt", "Old.txt") == 0)
    {
        try
        {
            ifstream in("Old.txt");
            ofstream out("Text.txt");
            string line;
            while (getline(in, line))
            {
                size_t pos = line.find("<--START-->");
                if (pos != string::npos)
                {
                    string remain = line.substr(pos + 11);
                    if (remain.size())
                        out << remain << endl;
                    break;
                }
            }
            while (getline(in, line))
                out << line << endl;
        }
        catch (exception&)
        {
            remove("Text.txt");
            rename("Old.txt", "Text.txt");
            cerr << "Error processing file" << endl;
            return 1;
        }
        remove("Old.txt");
        return 0; 
    }
    cerr << "Error renaming file, access right?" << endl;
    return 2; 
} 

这篇关于C ++重写一个文件,但在一个单词之前省略一切的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆