标题:bidirectional io: how do you shorten file length?
取消只看楼主
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
 问题点数:0 回复次数:2 
bidirectional io: how do you shorten file length?

I was asked a question about fstream a few days:

How do you shorten the file length of a bidirectional io? A requirement is that we can only open the stream once.

I tried to write the following code, but it failed.
======================================

#include <iostream>
#include <string>
#include <fstream>

/** Original content of a.txt is
aba

After running the program, I want the modified content to be
aa

This means that I have to shorten the file size by 1 byte.
*/


using namespace std;

int main()
{
fstream fs("a.txt", ios::in | ios::out);
string s;

fs>>s;
cout<<s<<endl; // s is "aba"
s.replace(s.find("b"), 1, "");
cout<<s<<endl; // s is "aa" now

fs.seekp(ios::beg);
fs.clear();

fs<<s; // this gives "aaa" since we don't shorten the file length

fs.close();

return 0;
}

搜索更多相关主题的帖子: file length shorten 
2007-08-27 11:57
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
得分:0 
to wfpb:

thanks for your soln. Don't know if this also works for Linux system.


I am working on a system which has no Chinese input. Please don\'t blame me for typing English.
2007-08-28 21:57
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
得分:0 
Win32 API

I guess it won't work for standard c++.

However, it is a platform-dependent soln.

I am working on a system which has no Chinese input. Please don\'t blame me for typing English.
2007-08-29 04:11



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-165697-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 1.529710 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved