C++ C语言 读写文件

来源:互联网 发布:激战2捏脸数据迪丽热巴 编辑:程序博客网 时间:2024/06/11 09:01
#include <iostream>
#include <fstream>
using namespace std;
 
int main()
{
    char filename[] = "..."; 
 
    /// 读
    fstream fin;  
    fin.open( filename );
    if ( !fin.is_open() ) // 检查文件是否成功打开 
    {
        cout<< "can't open file" << endl;
        fin.clear();
        fin.close();
        return 1;
    }
 
    int i;  
    fin>>i; //从文件输出一个整数值。 
 
    fin.clear();
    fin.close();
    
    ////////////////////////////////////////////////////////////////
 
    /// 写
    ofstream fout;
    fout.open(filename);
    if ( !fout.is_open() ) // 检查文件是否成功打开 
    {
        cout<< "can't open file" << endl;
        fout.clear();
        fout.close();
        return 1;
    }
    fout << ....; // fout用法和cout一致, 不过是写到文件里面去
    fout.clear();
    fout.close();
 
    return 0;
}
 
///////////////////////////////////////////////////////////////////////
open 函数:
 
void open(const char* filename,int mode,int access);  
参数:  
filename:  要打开的文件名  
mode:    要打开文件的方式  
access:   打开文件的属性  
 
打开文件的方式在类ios(是所有流式I/O类的基类)中定义,常用的值如下:  
ios::app:   以追加的方式打开文件  
ios::ate:   文件打开后定位到文件尾,ios:app就包含有此属性  
ios::binary: 以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文  
ios::in:    文件以输入方式打开(文件数据输入到内存)  
ios::out:   文件以输出方式打开(内存数据输出到文件)  
ios::nocreate: 不建立文件,所以文件不存在时打开失败  
ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败  
ios::trunc:  如果文件存在,把文件长度设为0  
  可以用“或”把以上属性连接起来,如ios::out|ios::binary  
 
打开文件的属性取值是:  
0:普通文件,打开访问  
1:只读文件  
2:隐含文件  
4:系统文件  

 

/// 读:
FILE *file;
char buf[MAX_PATH];
int len = 0, i = 0;
char *array = NULL;
 
file = fopen( "..\\Path.txt”, ”r” );
if( !file )
{
    return 1;
}
while( fgets( buf, MAX_PATH, file ) )
{
    len = strlen( buf );
    array = ( char* )malloc( len+1 );
    if( !array )
    {
        break;
    }
    strcpy( array, buf );
}
 
这个函数只读一行,如果想读多行,可将array设置为数组
 
/// 写:
FILE *file;
file = fopen( “..\\path.txt”, ”w” ); 
fputs( szPath, file ); 
版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明http://shijuanfeng.blogbus.com/logs/210210425.html
原创粉丝点击