c++ - 在 Linux 中使用 fstream

标签 c++ linux

我想我有一个初学者的问题。

我尝试逐行读取文件。

该文件位于/home/myhomedir 中,名为 text.txt 。 文件内容为

1
2
3
4

该文件具有访问权限,所有人都可以读写。

我想要:打开文件并逐行阅读。

所以我尝试了:

#include <cstdlib>
#include <iostream>
#include <fstream> 

using namespace std;

int main(int argc, char** argv) 
{
    try
    {
        ifstream myfile ;
        myfile.open("/home/myhomedir/text.txt", ios::in);
        if(myfile.is_open())
        {
            string line;

            while (getline(myfile, line)) {
               // do nothing, just get a line
               // *
            }
        }
    }
    catch(int ex)
    {
    }

    return 0;
}

已经到达*标记的地方(使用了netbeans的debug特性)。然而,这一行是空的,循环似乎只输入了一次。

就像打开一个空文件一样。

我做错了什么?

最佳答案

原因是,你不知道如何使用调试器。我修改了你的代码:

#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char** argv)
{
    try
    {
        ifstream myfile ;
        myfile.open("/home/enedil/text.txt", ios::in);
        if(myfile.is_open())
        {
            string line;

            while (getline(myfile, line)) {
                cout << line; // there's my modification
            }
        }
    }
    catch(int ex)
    {
    }

    return 0;
}

输出是

1234

所以一切都是正确的。

关于c++ - 在 Linux 中使用 fstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23322614/

相关文章:

linux - SVN错误: Subcommand 'help' doesn't accept option '--no-auth-cache'

c++ - 简单聊天机器人的段错误(核心转储)

linux - 如何大写所有文件名

c - 如何在c中确定linux中的目录或文件

c++ - 我应该在私有(private)项目中使用私有(private)类(class)吗?

linux - 比较文件的两列在 linux 中是否相同

android - 如何从 Linux 内核中找到处理核心的频率和利用率?

c++ - 将 atan2 与类模板一起使用失败,对重载函数的调用不明确

C# DLL 到 .il,到 C++ DLL : problem with strings

c++ - "missing return statement",但我知道它在那里