简体   繁体   English

使用CFile检查换行符(换行符)

[英]Checking line breaks (newline characters) with CFile

I need to check whether a file is ended with a line break or not, using CFile . 我需要使用CFile检查文件是否以换行符结尾。 What I have tried: 我试过的

  1. point the file pointer at the end of the file 将文件指针指向文件末尾
  2. move the pointer back by 2 units 向后移动指针2个单位
  3. check if the pointer is pointing at \\r\\n 检查指针是否指向\\r\\n

Here is my code: 这是我的代码:

cfile.SeekToEnd();
cfile.Seek(-2, CFile::current);
char buffer[2];
cfile.Read(buffer, 2);
if(buffer[0] == '\r' && buffer[1] == '\n') printf("Ended with line break!");
else printf("Not ended with line break!");

However, what I found is that the buffer gives me a \\n character and a garbage character (with weird values like 204). 但是,我发现缓冲区为我提供了\\n字符和无用字符(具有类似204的怪异值)。 After some research through the documentation, I found that CFile::Read only count \\r\\n as a single character: 通过文档研究后,我发现CFile::Read仅将\\r\\n为单个字符:

For text-mode files, carriage return–linefeed pairs are counted as single characters. 对于文本模式文件,回车换行符对被视为单个字符。

I am so confused because the file pointer obviously still counts 2 characters but I cannot get both of them. 我很困惑,因为文件指针显然仍然计数2个字符,但我无法同时获得它们。 Is there any method to check line break at the end of a file with CFile? 有没有什么方法可以使用CFile检查文件末尾的换行符?

I solved the problem by using CFile::typeBinary when opening a file. 我通过打开文件时使用CFile::typeBinary解决了该问题。

It seems that CFile::typeText do something special processing carriage return–linefeed pairs (eg filling in a garbage character which is supposed to be a carriage return) which is not desired in my case. 似乎CFile::typeText做了一些特殊的处理回车换行符对(例如,填写应该是回车的垃圾字符),这在我的情况下是不希望的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM