C++ 如何检查文件最后一行的新行字符?C++;

C++ 如何检查文件最后一行的新行字符?C++;,c++,file,newline,eof,getline,C++,File,Newline,Eof,Getline,如何检查文件中的最后一行是否包含“\n”(或换行符) 以下是两个例子: - 我当前的代码: fstream file("filename"); string line; if (!file.is_open()) throw Exception(); while(getline(file, line)) { (checking for lastline) } 我意识到getline将不包含新行字符。我可以浏览每个角色,但会有一个性能问题。有数百万个字符的文件,我不知道如何到最后一行获取

如何检查文件中的最后一行是否包含“\n”(或换行符)

以下是两个例子: -

我当前的代码:

fstream file("filename");
string line;
if (!file.is_open()) throw Exception();
while(getline(file, line))
{
    (checking for lastline)
}
我意识到getline将不包含新行字符。我可以浏览每个角色,但会有一个性能问题。有数百万个字符的文件,我不知道如何到最后一行获取新的字符

---编辑---

  • 也许我忘了提到我的环境是UNIX。所以我会的 仅使用结束字符“\n”
  • 其次,我需要getline检查每一行是否有错误(但在这里并不相关)
  • 我会在while循环之前检查我的最后一行,这样如果文件无效,我可以sip它
  • 我的照片显示了我的坏习惯。为错误道歉。应该只有你自己

有三种不同的方法来指示新行

  • 两个字符CR LF(\r\n):DOS、OS/2、Microsoft Windows、Symbian、DEC RT-1 1
  • 单字符CR(\r):Commodore、Apple II、Mac OS(直到版本9)、Microware OS-9
  • 单字符LF(\n):Unix、BeOS、AmigaOS、MorphOS、RISC OS、GNU/Linux、Mac OS X、Multics
不要使用getline(),它将吃掉新行字符。在二进制模式下使用read()(参见Cheers和hth.-Alf comment)。文本模式将替换每个新行标记CR LF和CR to LF。在您的示例中,您有CR LF标记

在二进制模式下,您必须将一个或两个字符减去文件长度,然后读取()两个字符,然后检查它们是否等于CR LF。参见Rishit示例。

您可以使用跳转到文件中的任何位置

file.seekg(-1,ios_base::end);    // go to one position before the EOF
char c;
file.get(c);                     // Read current character
if(c=='\n'){
    cout<<"yes"<<endl;           // You have new_line character
}
file.seekg(-1,ios_base::end);//转到EOF前的一个位置
字符c;
file.get(c);//读取当前字符
如果(c=='\n'){
你可以用

fgets(string_name, buffer_size, stdin)
fgets()包含新行字符,与get()和
fputs()不包括新行字符,不像puts()那样

例如:

while( fgets(str, sizeof(str), stdin) ) {
    // check newline at end of string
    int len = strlen(str);

    if( str[ len-1 ] != '\0' ) {
        str[ len-1 ] = '\0'; // make sure there's no new_line at the end
        len--;
    }

    // now check for empty string, if thus, then last line
    if( strcmp(str, "") == 0 ) break;
}

getline的问题是,它读取行并将其放入std::string,但会去除新行字符。您需要的是使用二进制模式读取函数。最困难的任务是让它找到所有可能的新行组合,并处理各种文件大小,最后使其看起来优雅。下面是我在h怎么做

问题是,例如,如果您的平台将新行存储为“\r\n”,那么如果\n或\r,也将在最后一行上作为新行计算

std::ofs流(“test.txt”);

ofs如何,搜索到底?请注意,对于文本模式,搜索通常非常简单,所以请在二进制模式下进行搜索,或者检查其支持与否的详细信息。“'\n'(或换行)”听起来这是一个非常不精确的要求。您真正想要实现什么?如果行比缓冲区长怎么办?那么其余的字符将在缓冲区中,它将接受输入,直到缓冲区未被清除。明白了。它将剩余的字符保留在缓冲区中,但将str中的最后一个字符替换为“\0”!!!is
if(str[len-1]!='\0')
应该是
if(str[len-1]='\n')
?(因为strlen会将len设置为str中第一个nul的索引,所以我能看到在索引len-1检测nul的唯一方法是如果str的长度为零(len为零)由于未检查此条件,因此可能会在字符串开始之前的索引-1处存在一个伪nul,但这肯定不是有意的)。
    std::ofstream ofs("test.txt");
    ofs << "test \n" << "test 2\n";
    //ofs << "\r";
    ofs.close();

    std::ifstream ifs("test.txt", std::ifstream::binary);

    // Read last two chars, it might also read only one last char
    std::vector<char> end_file_chars;
    for (int pos = 1; pos <= 2; ++pos) {
        if (!ifs.seekg(-pos, std::ios::end)) break;
        char c;
        if (ifs.get(c)) end_file_chars.insert(end_file_chars.begin(), c);
    }

    // Possible end file characters
    std::vector<std::vector<char>> endlines = {{'\r', '\n'},
                                               {'\n'},
                                               {'\r'}};

    // Predicate to compare possible endline with what was found in the file.
    auto checkFn = [&](auto &endline) {
        // Equal compares possible endline in reverse order
        return std::equal(endline.rbegin(), endline.rend(), end_file_chars.rbegin());
    };

    // If any end file character was read and if it acually is end file character...
    if (!end_file_chars.empty() && std::find_if(endlines.begin(), endlines.end(),checkFn) != endlines.end()) {
        std::cout << "Found";
    }
    else {
        std::cout << "Not Found";
    }