打印出文件的最后 10 行

发布于 2024-11-03 11:13:27 字数 1260 浏览 1 评论 0原文

我希望能够选择打印文本文件的最后 10 行。使用这个程序,我已经能够读取整个文本文件,但我无法弄清楚如何操作保存文本文件的数组,有什么帮助吗?

// Textfile output
#include<fstream>
#include<iostream>
#include<iomanip>
using namespace std;

int main() {
    int i=1;
    char zeile[250], file[50];
    cout << "filename:" << flush;
    cin.get(file,50);                          ///// (1)
    ifstream eingabe(datei , ios::in);          /////(2)
    if (eingabe.good() ) {                       /////(3)           
       eingabe.seekg(0L,ios::end);               ////(4)
       cout << "file:"<< file << "\t"
            << eingabe.tellg() << " Bytes"       ////(5)
            << endl;
       for (int j=0; j<80;j++)
           cout << "_";
           cout << endl;
       eingabe.seekg(0L, ios::beg);              ////(6)
       while (!eingabe.eof() ){                  ///(7)
             eingabe.getline(zeile,250);         ///(8)
             cout << setw(2) << i++
                  << ":" << zeile << endl;
             }      
           }
    else
        cout <<"dateifehler oder Datei nicht gefunden!"
             << endl;
            
             return 0;
    }

I want to have the option to print out the last 10 lines of a textfile . with this program I've been able to read the whole textfile, but I can't figure out how to manipulate the array in which the textfile is saved, any help?

// Textfile output
#include<fstream>
#include<iostream>
#include<iomanip>
using namespace std;

int main() {
    int i=1;
    char zeile[250], file[50];
    cout << "filename:" << flush;
    cin.get(file,50);                          ///// (1)
    ifstream eingabe(datei , ios::in);          /////(2)
    if (eingabe.good() ) {                       /////(3)           
       eingabe.seekg(0L,ios::end);               ////(4)
       cout << "file:"<< file << "\t"
            << eingabe.tellg() << " Bytes"       ////(5)
            << endl;
       for (int j=0; j<80;j++)
           cout << "_";
           cout << endl;
       eingabe.seekg(0L, ios::beg);              ////(6)
       while (!eingabe.eof() ){                  ///(7)
             eingabe.getline(zeile,250);         ///(8)
             cout << setw(2) << i++
                  << ":" << zeile << endl;
             }      
           }
    else
        cout <<"dateifehler oder Datei nicht gefunden!"
             << endl;
            
             return 0;
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

离鸿 2024-11-10 11:13:28

我在这里研究了建议的方法,并在我的博客文章中描述了所有内容。有一个更好的解决方案,但您必须跳到最后并保留所有需要的行:

std::ifstream hndl(filename, std::ios::in | std::ios::ate);
// and use handler in function which iterate backward
void print_last_lines_using_circular_buffer(std::ifstream& stream, int lines)
{
    circular_buffer<std::string> buffer(lines);

    std::copy(std::istream_iterator<line>(stream),
              std::istream_iterator<line>(),
              std::back_inserter(buffer));

    std::copy(buffer.begin(), buffer.end(),
            std::ostream_iterator<std::string>(std::cout));
}

I investigate proposed approaches here and describe all in my blog post. There is a better solution but you have to jump to the end and persist all needed lines:

std::ifstream hndl(filename, std::ios::in | std::ios::ate);
// and use handler in function which iterate backward
void print_last_lines_using_circular_buffer(std::ifstream& stream, int lines)
{
    circular_buffer<std::string> buffer(lines);

    std::copy(std::istream_iterator<line>(stream),
              std::istream_iterator<line>(),
              std::back_inserter(buffer));

    std::copy(buffer.begin(), buffer.end(),
            std::ostream_iterator<std::string>(std::cout));
}
埖埖迣鎅 2024-11-10 11:13:27

试试这个:

#include <list>
#include <string>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>

// 一个知道如何使用运算符 >> 读取一行的类

struct Line
{
    std::string theLine;
    operator std::string const& () const { return theLine; }
    friend std::istream& operator>>(std::istream& stream, Line& l)
    {
        return std::getline(stream, l.theLine);
    }
};

// 一个循环缓冲区,仅保存最后 n 行。

class Buffer
{
    public:
        Buffer(size_t lc)
            : lineCount(lc)
        {}
        void push_back(std::string const& line)
        {
            buffer.insert(buffer.end(),line);
            if (buffer.size() > lineCount)
            {
                buffer.erase(buffer.begin());
            }
        }
        typedef std::list<std::string>      Cont;
        typedef Cont::const_iterator        const_iterator;
        typedef Cont::const_reference       const_reference;
        const_iterator begin()  const       { return buffer.begin(); }
        const_iterator end()    const       { return buffer.end();}

    private:
        size_t                      lineCount;
        std::list<std::string>      buffer;
};    

// 主要的

int main()
{
    std::ifstream   file("Plop");
    Buffer          buffer(10);

    // Copy the file into the special buffer.
    std::copy(std::istream_iterator<Line>(file), std::istream_iterator<Line>(),
            std::back_inserter(buffer));

    // Copy the buffer (which only has the last 10 lines)
    // to std::cout
    std::copy(buffer.begin(), buffer.end(),
            std::ostream_iterator<std::string>(std::cout, "\n"));
}

Try this:

#include <list>
#include <string>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>

// A class that knows how to read a line using operator >>

struct Line
{
    std::string theLine;
    operator std::string const& () const { return theLine; }
    friend std::istream& operator>>(std::istream& stream, Line& l)
    {
        return std::getline(stream, l.theLine);
    }
};

// A circular buffer that only saves the last n lines.

class Buffer
{
    public:
        Buffer(size_t lc)
            : lineCount(lc)
        {}
        void push_back(std::string const& line)
        {
            buffer.insert(buffer.end(),line);
            if (buffer.size() > lineCount)
            {
                buffer.erase(buffer.begin());
            }
        }
        typedef std::list<std::string>      Cont;
        typedef Cont::const_iterator        const_iterator;
        typedef Cont::const_reference       const_reference;
        const_iterator begin()  const       { return buffer.begin(); }
        const_iterator end()    const       { return buffer.end();}

    private:
        size_t                      lineCount;
        std::list<std::string>      buffer;
};    

// Main

int main()
{
    std::ifstream   file("Plop");
    Buffer          buffer(10);

    // Copy the file into the special buffer.
    std::copy(std::istream_iterator<Line>(file), std::istream_iterator<Line>(),
            std::back_inserter(buffer));

    // Copy the buffer (which only has the last 10 lines)
    // to std::cout
    std::copy(buffer.begin(), buffer.end(),
            std::ostream_iterator<std::string>(std::cout, "\n"));
}
终遇你 2024-11-10 11:13:27

基本上,您不会将文件内容保存到任何数组中。以下示例将为您提供一个良好的开端:

#include <iostream>
#include <vector>
#include <string>

int main ( int, char ** )
{
    // Ask user for path to file.
    std::string path;
    std::cout << "filename:";
    std::getline(std::cin, path);

    // Open selected file.      
    std::ifstream file(path.c_str());
    if ( !file.is_open() )
    {
        std::cerr << "Failed to open '" << path << "'." << std::endl;
        return EXIT_FAILURE;
    }

    // Read lines (note: stores all of it in memory, might not be your best option).
    std::vector<std::string> lines;
    for ( std::string line; std::getline(file,line); )
    {
        lines.push_back(line);
    }

    // Print out (up to) last ten lines.
    for ( std::size_t i = std::min(lines.size(), std::size_t(10)); i < lines.size(); ++i )
    {
        std::cout << lines[i] << std::endl;
    }
}

避免将整个文件存储到内存中可能是更明智的做法,因此您可以通过这种方式重写最后 2 个段:

// Read up to 10 lines, accumulating.
std::deque<std::string> lines;
for ( std::string line; lines.size() < 0 && getline(file,line); )
{
    lines.push_back(line);
}

// Read the rest of the file, adding one, dumping one.
for ( std::string line; getline(file,line); )
{
    lines.pop_front();
    lines.push_back(line);
}

// Print out whatever is left (up to 10 lines).
for ( std::size_t i = 0; i < lines.size(); ++i )
{
    std::cout << lines[i] << std::endl;
}

Basically, you are not saving the file contents to any array. The following sample will give you a head start:

#include <iostream>
#include <vector>
#include <string>

int main ( int, char ** )
{
    // Ask user for path to file.
    std::string path;
    std::cout << "filename:";
    std::getline(std::cin, path);

    // Open selected file.      
    std::ifstream file(path.c_str());
    if ( !file.is_open() )
    {
        std::cerr << "Failed to open '" << path << "'." << std::endl;
        return EXIT_FAILURE;
    }

    // Read lines (note: stores all of it in memory, might not be your best option).
    std::vector<std::string> lines;
    for ( std::string line; std::getline(file,line); )
    {
        lines.push_back(line);
    }

    // Print out (up to) last ten lines.
    for ( std::size_t i = std::min(lines.size(), std::size_t(10)); i < lines.size(); ++i )
    {
        std::cout << lines[i] << std::endl;
    }
}

It would probably be wiser to avoid storing the whole file into memory, so you could re-write the last 2 segments this way:

// Read up to 10 lines, accumulating.
std::deque<std::string> lines;
for ( std::string line; lines.size() < 0 && getline(file,line); )
{
    lines.push_back(line);
}

// Read the rest of the file, adding one, dumping one.
for ( std::string line; getline(file,line); )
{
    lines.pop_front();
    lines.push_back(line);
}

// Print out whatever is left (up to 10 lines).
for ( std::size_t i = 0; i < lines.size(); ++i )
{
    std::cout << lines[i] << std::endl;
}
扭转时空 2024-11-10 11:13:27

eof() 函数并没有做你和其他一百万个 C++ 新手所认为的那样的事情。它不会预测下一次读取是否有效。在 C++ 中,与任何其他语言一样,您必须检查每个读取操作的状态,而不是读取之前输入流的状态。所以规范的 C++ 读取行循环是:

while ( eingabe.getline(zeile,250) ) {
    // do something with zeile
}

另外,您应该读入 std::string,并去掉 250 值。

The eof() function does not do what you and it seems a million other C++ newbies think it does. It does NOT predict if the next read will work. In C++ as in any other language, you must check the status of each read operation, not the state of the input stream before the read. so the canonical C++ read line loop is:

while ( eingabe.getline(zeile,250) ) {
    // do something with zeile
}

Also, you should be reading into a std::string, and get rid of that 250 value.

分分钟 2024-11-10 11:13:27

创建一个具有 10 个槽的循环缓冲区,并在读取文件行时将它们放入该缓冲区中。完成 thr 文件后,执行position++ 转到第一个元素并将其全部打印。
如果文件少于 10 行,请注意空值。

Do a circular buffer with 10 slots and while reading the file lines, putting them into this buffer. When you finish thr file, do a position++ to go to the first element and print them all.
Pay attention for null values if the file has less than 10 lines.

探春 2024-11-10 11:13:27
  1. 有一个大小为 10 的字符串数组。
  2. 读取第一行并将其存储到数组中
  3. 继续读取直到数组已满
  4. 一旦数组已满,请删除第一个条目,以便您可以输入新行
    重复步骤3和4,直到文件读取完毕。
  1. Have an array of strings with size 10.
  2. Read the first line and store into the array
  3. Continue reading till the array is full
  4. Once the array is full delete the first entry so that you can enter new line
    Repeate step 3 and 4 till the file is finished reading.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文