您的位置:首页 > 编程语言 > C语言/C++

C语言、C++文件操作汇总

2017-12-10 16:56 267 查看

1.C语言文件操作

C language:

FILE* fp;

char ch;

注意是“r”而非‘r’

fp = fopen(“1.txt”, “r+”);//读写,除此之外用得比较多的有”a+”追加(也有读权限)

if( NULL = fp)

printf(“Failed to open the file”);

ch = getchar();

//读写一个字符

fputc(ch, fp);//向文件输入一个字符,成功则返回字符ch,失败则返回EOF(-1)

ch = putchar();//将ch显示咋屏幕上

……

while(!feof(fp)){

ch = fgetc(fp);//从文件中获取(读入)一个字符,返回同上

}

//读写字符串

char str[200] = “123456779804254504358045405;

char str[10];

fputs(str, fp);//将str中的字符写入到文件中,成功则返回0

rewind(fp);//将文件读写位置标记重新指向文件开头,很重要

fseek(fp, 2, 0);//将文件读写位置标记指向离开头偏移为1(第二个字符)的位置;

char * ret = fgets(str1, 10, fp);//从文件读取9个长度的字符,失败则返回NULL

if ( ret != NULL)

printf(“%s”,str1);

fclose(fp);

//格式化读写文件:

fprintf(fp, “%d, %6.2f”,i, j);//将变量i,j内容按照指定格式输入到fp所指向的文件中

fscanf(fp, “%d, %f”, &i, &j);//从文件中获取内容。如果文件中有2,5则i = 2,j=5

fp = fopen(“1.dat”,”rb+”);//读写二进制文件

float buf[10] = {0,1,2,3,4,5,6,7,8,9};

float buff[10];

//二进制读写文件

fwrite(buf, 10, sizeof(float), fp);//从buf的数据中写10个4个字节大小的数据块 (即10个float变量)到文件fp

fread(buff, 10, sizeof(float), fp);//读文件到buff;

附录

1.文件指针结构体FILE中有文件位置标记,会随着读写改变;它总是指向“接下来要读或写的一个字符的位置”

2fseek(fp, 位移量, 起始点);其中起始点有0,1,2,分别表示文件开头,当前读写位置,文件结束点;位移量可以为负;

2.系统定义了stdin,stdout,stderr三个“文件指针”指向输入输出流和错误输出流,因此可以用:

fputc(ch, stdout);ch = fgetc(stdin);

exit():结束程序所在的进程(这个过程中会先释放内存,并检查文件状态,将文件缓冲区的内容写到文件)

exit(0)//正常结束进程

exit(1)//异常结束进程

2.C++ 文件操作

1.read from file

ifstream in; in.open(“1.txt”);

if (!in.is_open())

{

cout << “CANNOT OPEN”<< endl;

continue;

}

char str[60];

in >> str;

std::cout << str << std::endl;

in.close();

2.write to file

ofstream out(“1.txt”,std::ios::out | std::ios::app);

out<<”haha\nhehe.”;

out.close();

3.read and write

std::fstream fs;

fs.open(“1.txt”, std::fstream::in | std::fstream::out);

char str[60] = “123456789”;

fs << str;

fs.seekp(std::ios::beg);//

fs >> str;//遇到空格等就返回,并且会跳过空格。多用getline之类

cout << str << endl;
fs.close();


MODE

in input File open for reading

out output File open for writing//

binary binary Operations are performed in binary mode rather than text.

ate at end The output position starts at the end of the file.

app append

trunc truncate Any contents that existed in the file before it is open are discarded.

二进制读写需要用 f.write,和f.read,而非<<和>>

设置文件指针位置:

1. ios::beg 文件头

2. ios::end 文件尾

3. ios::cur 当前位置

seekp() //写入 如cout, ofstream

seekg() //读入,比如cin, ifstream

fs.seekp(std::ios::beg, 10),std::ios::cur,std::ios::end

常见错误判断方法:

1. fs.good() 如果文件打开成功

2. fs.bad() 打开文件时发生错误

3. fs.eof() 到达文件尾

其他重要公共成员函数:

get和getline:从流中获取/读入数据到变量中

char str[256];

cin.get(ch);//读入单个字符

对于getline,不论是fs.getline,还是std::getline,都是遇到’s’(不会包含s)就停止;遇到\n也停止想,下一次getline就从没开始的部分(比如’s’之后的字符或者下一行)开始。

fs.get (str,256); // get c-string,还可以:

fs.get(str, 256, ‘s’);//遇到最大长度255(n-1)会停止

string sStr;

getline(fs,sStr,’s’);//#include

3.一些其他的文件操作:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: