同时读写文件
本帖最后由 luckstudent 于 2017-8-12 00:36 编辑int main()
{
fstream inOut("C:\\Users\\lucks\\Desktop\\C++\\text.txt", fstream::ate | fstream::in | fstream::out);
size_t cnt = 0;
string line;
auto endMark = inOut.tellg();
inOut.seekg(0, fstream::beg);
while(getline(inOut, line) && inOut && inOut.tellg() != endMark)
{
cnt = line.size() + 1;
auto tempmark = inOut.tellg();
inOut.seekp(0, fstream::end);
inOut << cnt;
if(tempmark != endMark)
inOut << " ";
inOut.seekg(tempmark);
}
inOut.seekp(0, fstream::end);
inOut << "\n";
return 0;
}
txt文档末输出每行字符数,但结果错误。求指点
在我的试验中是没有问题的:#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream inOut("inout.txt", fstream::ate | fstream::in | fstream::out);
size_t cnt = 0;
string line;
auto endMark = inOut.tellg();
inOut.seekg(0, fstream::beg);
while (getline(inOut, line) && inOut && inOut.tellg() != endMark) {
cnt = line.size() + 1;
auto tempmark = inOut.tellg();
inOut.seekp(0, fstream::end);
inOut << cnt;
if (tempmark != endMark)
inOut << " ";
inOut.seekg(tempmark);
}
inOut.seekp(0, fstream::end);
inOut << "\n";
return 0;
}
其中的 inout.txt 文件内容如下:
line1: hello
line2: world!!!
line3: 012314
line4: 01231484
line5: 012314484
注意最后留了个空行,输出结果如下:
line1: hello
line2: world!!!
line3: 012314
line4: 01231484
line5: 012314484
13 16 14 16
当然我把 inout.txt 的换行存为 unix-style,也就是 LF 而不是 CRLF,所以第一行统计的数目为13。
你的统计结果有问题我估计是修改后没有即时保存。我用的比较简单的vscode编辑器,即时观察输出效果:
我原来是Code::Blocks写的 换成VS2013也没问题。感觉是Code::Blocks自身的问题。看下面代码
int main()
{
fstream inOut("C:\\Users\\lucks\\Desktop\\C++\\text.txt", fstream::ate | fstream::in | fstream::out);
fstream out("C:\\Users\\lucks\\Desktop\\new.txt", fstream::out);
int cnt = 0;
string line;
auto endMark = inOut.tellg();
inOut.seekg(0, fstream::beg);
while(getline(inOut, line) && inOut && inOut.tellg() != endMark)
{
/*auto tempMark = inOut.tellg();
inOut.seekp(0, fstream::end);
inOut.seekg(tempMark);*/
cnt = line.size() + 1;
out << cnt << line << endl;
}
return 0;
}
此程序的就是把源文档的每行字符个数加字符输出到新的文档中去。如果没有注释部分,能出来正确结果。但是如果把注释部分加上去,那么Code::Blocks就出问题了,VS2013还是正确的。有大神能输出具体原因么。
页:
[1]