注册 登录
编程论坛 C++教室

bidirectional io: how do you shorten file length?

HJin 发布于 2007-08-27 11:57, 633 次点击

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;
}

6 回复
#2
aipb20072007-08-27 13:34
能打开两次还好,一次似乎很困难呢。

mark。
#3
wfpb2007-08-28 14:28
以下是引用HJin在2007-8-27 11:57:37的发言:

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()
{
HANDLE hFile=CreateFile("F:\\1.txt",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0, &hFile);
char buf[MAX_PATH]={0};
DWORD readLen=0;
int size=ReadFile(hFile,buf,MAX_PATH,&readLen,NULL);
string s=string(buf);
cout<<s<<endl; // s is "aba"
s.replace(s.find("b"), 1, "");
cout<<s<<endl; // s is "aa" now
SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
SetEndOfFile(hFile);
WriteFile(hFile,s.c_str(),s.length(),&readLen,NULL);
CloseHandle(hFile);

return 0;
}

API有设置结尾的函数
#4
HJin2007-08-28 21:57
to wfpb:

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

#5
aipb20072007-08-29 00:33
wfpb
那时vc吗?
#6
HJin2007-08-29 04:11
Win32 API

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

However, it is a platform-dependent soln.
#7
wfpb2007-08-29 16:30

sorry,i can't help you !

1