文件末尾的 C++ 进程文件空行
c++ process file blank line at the end of file
当我使用c++处理文件时,发现文件末尾总是有一个空行。有人说 vim 会在文件末尾附加一个"",但是当我使用 gedit 时,它也有同样的问题。谁能告诉我原因?
1 #include<iostream>
2 #include<fstream>
3
4 using namespace std;
5 const int K = 10;
6 int main(){
7 string arr[K];
8 ifstream infile("test1");
9 int L = 0;
10 while(!infile.eof()){
11 getline(infile, arr[(L++)%K]);
12 }
13 //line
14 int start,count;
15 if (L < K){
16 start = 0;
17 count = L;
18 }
19 else{
20 start = L % K;
21 count = K;
22 }
23 cout << count << endl;
24 for (int i = 0; i < count; ++i)
25 cout << arr[(start + i) % K] << endl;
26 infile.close();
27 return 1;
28 }
while test1 file just:
abcd
but the program out is :
2
abcd
(upside is a blank line)
while(!infile.eof())
infile.eof()
仅在您尝试读取文件末尾之后才是正确的。因此,循环尝试读取比实际多一行,并在该尝试中获得一个空行。
这是一个顺序问题,您正在阅读,分配并在检查后...您应该稍微更改一下代码,以便读取、检查和分配:
std::string str;
while (getline(infile, str)) {
arr[(L++)%K] = str;
}
http://www.parashift.com/c++-faq-lite/istream-and-eof.html
如何在 c++ 中使用 getline() 时确定它是否为 EOF
相关文章:
- c++多进程编写一个唯一的文件
- 避免使用 boost::进程间::消息队列创建文件
- 从根权限进程创建可访问的文件
- Windows 将标准的 C 文件结构注入到正在运行的进程中
- gcc 找不到 -lgcc, g++.exe: 错误: 创建进程: 没有这样的文件或目录
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?
- 如何在 Linux 下使用 c++ 知道文件是否被其他进程使用?
- 多个线程/进程是否可以在不同步的情况下同时从/写入文件的非重叠区域?
- 如何检测哪些进程更改,重命名或创建文件?
- 如何:监视Windows中另一个进程的文件访问?
- 提升进程间共享内存删除、权限和输出文件
- 使用文件锁定的进程之间的条件变量
- 当多个进程尝试同时替换同一文件时,Linux 如何处理这种情况?
- COM 客户端连接 COM 服务器所需的文件是什么(进程外方案)
- 如何在我的进程中运行的二进制文件中注册操作和内核
- 为什么我的 Redhat 服务器上的 QuickFIX 进程没有将其核心文件写入应有的位置?
- Growing Boost.使用单个写入器的进程间内存映射文件
- C++ Mingw32 创建进程() 失败,错误代码 2:系统找不到指定的文件
- 如何从安卓原生二进制文件运行单独的进程
- Python 子进程.Popen 在 g++ 中编译,自动添加.cpp文件