C ++ fstream read&写 [英] C++ fstream read & write
问题描述
关于如何阅读文件,我有一个简短的问题。具体来说,你怎么能一次读取一个文件的大约100个字符,然后将相同的字符写入同一个文件。如果你想在一个文件上运行xor op而不使用除源之外的任何文件,那就好了。
我尝试过:
这个
无效main()
{
int theSize = 32;
char * data = new char [36];
fstream fileStreamIn(in,ios :: in | ios :: out | ios :: binary);
while(fileStreamIn)
{
fileStreamIn.read(data,theSize);
size_t count = fileStreamIn.gcount();
cout<<数据;
fileStreamIn<<数据;
fileStreamIn.write(数据,计数);
}
fileStreamIn.close();
系统(暂停);
}
I have a brief question as to how you would read a file. Specifically how could you read about 100 characters of a file at a time then write the very same characters to the same file.Like if you wanted to run an xor op on a file without using any file other than the source.
What I have tried:
This
void main ()
{
int theSize = 32;
char *data = new char[36];
fstream fileStreamIn("in",ios::in | ios::out | ios::binary);
while(fileStreamIn)
{
fileStreamIn.read(data,theSize);
size_t count = fileStreamIn.gcount();
cout << data;
fileStreamIn << data;
fileStreamIn.write(data,count);
}
fileStreamIn.close();
system("pause");
}
推荐答案
阅读很简单:你已经这样做了。
写作很容易:你也是这样做的。
所需要的就是寻找职位: istream :: seekg - C ++参考a> [ ^ ]
值得注意的是,如果您从Read切换到Write,反之亦然,那么无论如何都要寻找合适的位置是个好主意,因为有些系统确实保持独立输入和输出指针。
Reading is easy: you are already doing that.
And writing is easy: you are doing that as well.
All you need to is Seek the position: istream::seekg - C++ Reference[^]
It's worth noting that if you are switching from Read to Write or vice versa, it's a good idea to seek the right position anyway, as some systems do maintain independent input and output pointers.
这篇关于C ++ fstream read&写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!