c/c++文件知识总结
//C语言 文件总结 //根据数据组织形式 文件分为 // 文本文件(每个文件存放一个字符,每个字符用一个ASCII码表示) //和二进制文件(以字节为单位存放二进制代码,二进制文件中数据的存储方式与内存中数据的存储方式完全形同) //c语言对文件的操作通过文件处理函数实现 //1、文件打开与关闭 //2、文件读写函数 //3、文件定位函数 //4、文件状态检测函数 #include "stdio.h" #include "stdlib.h" int main(int argc, char* argv[]) { char ch; FILE *fp;//定义文件指针变量 fp=fopen("letter.txt","w");//打开文件 返回值:success返回文件地址 fail返回NULL //参数:1、文件路径(在当前目录下,可以只用文件名;否则给出文件路径)2、打开方式 //e.g.: fp=open("c:\\test\\file8_1.c","r"); if(fp==NULL) { printf("Opening file error\n"); exit(0); } for(ch='A';ch<='Z';ch++) fputc(ch,fp);//写入 do { ch=fgetc(fp); putchar(ch); }while(ch!=EOF);//EOF是文本文件结束的标志 fclose(fp);//关闭文件 返回值: success 0 fail 非0 return 0; } //2、字符读写 fgetc(fp) fputc(ch,fp) 返回值: success 字符 fail EOF //字符串读写 fgets(str,n,fp) 从fp中读取n-1个字符(遇到'\n'orEOF提前结束) 返回值: success str指针 fail null // fput(str,fp) 返回值: success 0 fail 非0 字符串结束标志'\0'不写入 fputs("\n",fp); //上面4种适用于文本文件 对于二进制文件通常使用数据块读写函数,来读写一组数据 //数据块读写 fread(&n,size,count,fp);参数:1、存放读入数据的首地址2、一块大小几个字节3、多少数据块4、文件指针 // 返回值: success count fail <count // fwrite(&n,size,count,fp) //格式化读写(对于两种文件均可)fscanf(fp,"%f%d",&price,&num); fprintf(fp,"%5.2f, %d\n",price,num); //返回值: success 操作字符数 fail EOF //3、文件定位 //复位函数 rewind(fp);(文件位置指针重新指向文件的开头) //随机移动函数 fseek(fp,20L,0);指针从开始向后移动20个字节 // fseek(fp,20L,1);指针从当前位置向后移动20个字节 // fseek(fp,-20L,2);指针从末尾向前移动20个字节fseek(fp,0,2); //获取当前位置 ftell(fp); 返回值: success 文件位置指针相对于文件开头的偏离量 fail -1 //4、文件检测函数 //检测文件是否已到末尾 文本文件可用EOF feof(fp)两种文件形式均适用(返回值:结束非0 未结束0) while(!feof(fp)) { ch=fgetc(fp); putchar(ch); n++; }
全面:
http://blog.jobbole.com/106992/
http://blog.sciencenet.cn/blog-411071-839543.html
http://panpan.blog.51cto.com/489034/101625
http://c.biancheng.net/cpp/biancheng/view/2227.html
//C++ 文件总结 #include "iostream" #include "fstream" #include "string" using namespace std; int main() { ofstream out;//创建一个输出文件对象实例out out.open("file.txt");//out与一文件关联 if(out.fail())//错误检查 有错返回true 否则false good()与之相反无错返回true 否则false 写入文件数据 { cerr<<"Failure to open file.txt for output"<<endl; return 1; } out<<"123456789abcdefghijklmn"<<endl; out.close(); char s,c,i; ifstream in("file.txt");//创建输入文件对象 从此文件中读取 while(!in.eof()) { in.get(c); cout<<c<<endl; } in.close(); ofstream out1("file.txt",ios::app);//追加 if(out1.fail()) { cerr<<"Open failure on file.txt"<<endl; return 1; } out1<<"This line is added to the end of the file"<<endl; out1<<endl<<endl<<endl<<endl<<"I have add four line "<<endl; out1.close(); ifstream in1("file.txt"); if(in1.fail()) { cerr<<"Open failure on file.txt"<<endl; return 1; } string cpp_string; int line_number=0;//从文件中读取行 while(getline(in1,cpp_string))//c-style string char c_string[81]; in1.getline(c_string,81); { cout<<++line_number<<":"<<cpp_string<<endl; } in1.close(); //随机存取随机定位 in.seekg(4,ios::beg);//=in.seekg(4); in.seekg(0,ios::beg);//开头 in.seekg(1,ios::cur); in.seekg(-3,ios::cur); in.seekg(0,ios::end);//结尾 in.seekg(-3,ios::end); return 0; }

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号