|
|
|
|
 C++文件操作的问题 - rainhard [ 2005-07-28 18:41 | 900 byte(s)]
 Re: C++文件操作的问题 - alula [ 2005-07-29 14:48 | 623 byte(s)]
 fstream 文件打开测试 - rainhard [ 2005-07-29 16:00 | 1,871 byte(s)]
 Re: fstream 文件打开测试 - alula [ 2005-07-29 17:07 | 692 byte(s)]
 Re: fstream 文件打开测试 - z_york [ 2005-07-29 17:47 | 206 byte(s)]
|
|
|
|
[Original]
[Print]
[Top]
|
c++ 如果文件不存在,则新建文件,程序如下:
文件不存在时,可以创建文件,可是文件是空的,为什么呢!
顺便问问,想向文件里写若干个0,怎么方便,谢谢!
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fs;
fs.open("ttt",ios::in|ios::binary|ios::out);
// fs.close();
if(!fs.is_open())
{
fs.open("ttt",ios::out|ios::binary);
int i =0;
int j =0;
while(i++<10)
// fs.put(j);
fs.write((const char*)&j,sizeof(int));
return -1;
}
return 0;
}
|
|
|
[Original]
[Print]
[Top]
|
|
[Original]
[Print]
[Top]
|
在第二次open 之前,调用fs.clear()。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fs;
fs.open("ttt",ios::in|ios::binary|ios::out);
// fs.close();
if(!fs.is_open())
{
fs.clear();
fs.open("ttt",ios::out|ios::binary);
int i =0;
int j =0;
while(i++<10)
// fs.put(j);
fs.write((const char*)&j,sizeof(int));
return -1;
}
return 0;
}
|
|
|
----
温故知新
|
|
[Original]
[Print]
[Top]
|
|
[Original]
[Print]
[Top]
|
谢谢alula!
为这个问题我做了些测试,结果记录如下,不正确和无知的地方请指正!
请问我看了一下资料,都没讲的很清楚,请牛哥介绍点资料,谢谢!
测试程序:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fs;
fs.open("exist",ios::in|ios::out);//测试文件是否存在
if(!fs){
cout<<"Not exist"<<endl;
fs.clear();
fs.open("exist",ios::out);//文件不存在,则新建一个文件,并填充内容
if(!fs)
cout<<"create Error"<<endl;
fs.write("test",5);
fs.close();
// fs.open("exist",ios::app|ios::out);// open and append data to end//1
// fs.open("exist",ios::app|ios::out|ios::in); //2
//加与不加ios::in(第1种)的区别在于,加了ios::in的话,无法打开文件
fs.open("exist",ios::out|ios::in);
//打开文件读写,可以在整个文件内移动
//与加ios::app(第2种)的区别在于,加了无法打开文件
//与第1种方式的区别是:第1种添加的内容始终在文件的末尾,
//即使移动偏移到文件头,如<YD>处的操作,也无法移动到原文件的开始位置,它的开始位置在原文件的末尾
// fs.open("exist",ios::ate|ios::out);//ate has no effect
//加了ate无法打开文件
//ate方式打开文件,没有作用,与不加的结果一样
fs.seekp(ios::beg);//<YD>
}
if(!fs)
cout<<"reopen fault"<<endl;
// fs.read();
fs.write("b",3);
}
|
|
|
[Original]
[Print]
[Top]
|
|
[Original]
[Print]
[Top]
|
<the C++ standard library> 有比较详尽的说明。
并不是任意的组合都行的,有效的组合:
in ____Reads (file must exist) "r"
out ____Empties and writes (creates if necessary) "w"
out | trunc ____Empties and writes (creates if necessary) "w"
out | app ____Appends (creates if necessary) "a"
in I out ____Reads and writes; initial position is the start (file must exist) "r+"
in | out | trunc ____Empties, reads, and writes (creates if necessary) "w+"
后面的引号内表示在C语言中对应的组合
|
|
|
----
温故知新
|
|
[Original]
[Print]
[Top]
|
|
[Original]
[Print]
[Top]
|
哈哈,用C语言直接多了,就几个标准C函数。
我看过一些源代码,发现用C++都不过是利用其面向对象的机制来架构一个framework而已,而具体的底层一点的细节,都是用C的方法去实现,比较少用到C++标准库。
|
|
|
----
I love David Beckham and Man.Utd. for ever.
|
|
[Original]
[Print]
[Top]
|
|
|