首页 > 编程知识 正文

数据结构知识点总结,c语言程序设计知识点总结

时间:2023-05-05 05:03:05 阅读:50473 作者:3556

c语言文件操作

1、文件:磁盘上的文件。 一般我们谈论的文件有程序文件和数据文件两种

程序文件:源文件的后缀为. c,目标文件的后缀为. obj,可执行程序(在windows环境中为. exe )。

数据文件:程序运行中需要读取的文件,或者输出内容的文件。

2、文件名:文件路径文件名骨干文件后缀

文件路径分为绝对路径和相对路径,两者如何区分?

绝对路径:例如,以驱动器号或根目录开头的C/D :

相对路径:以.或…开头,但前提是您必须位于当前目录中才能谈论相对路径。 以. 开头的表示当前路径,以…开头的表示当前路径的更高级别路径。

3、文件类型

区分二进制文件和文本文件

假设在文件中保存数字1,文本文件的保存方法为‘1’; 二进制文件的保存方法为000000000000000000000000000000000000000000000000000000001。 另一种方法是,要将文本文件输出到外部存储,必须先进行转换,然后将其另存为ASCII码。 二进制文件以二进制格式保存。

4、文件操作的函数

fopen:文件的打开函数

file * fopen (常数char * filename,常数char * mode );

返回值:

If the file is successfully opened,thefunctionreturnsapointertoafileobjectthatcanbeusedtoidentifythestreamonfutureoperations。

Otherwise,a null pointer is returned。

On most library implementations,theerrnovariableisalsosettoasystem-specificerrorcodeonfailure。

#includeint main () {

file*FP=fopen('./test.txt ',' r ' );

if(FP==null ) {

打印故障(n );

}else{

打印机(fopen success (n ) );

}

返回0;

}

如果经常打开或不关闭文件,会发生什么问题?

由于资源的泄漏是文件描述符的泄漏,因此fopen与fclose结合使用。

fclose:文件的关闭函数

int fclose (文件*流);

返回值:

ifthestreamissuccessfullyclosed,a zero value is returned。

On failure,EOF is returned。

#includeint main () {

file*FP=fopen('./test.txt ',' r ' );

if(FP==null ) {

打印故障(n );

}else{

打印机(fopen success (n ) );

}

流量(FP );

返回0;

}

fread:文件的读取函数是将磁盘上的数据读取到内存中。

size_tfread(void*ptr,size_t size,size_t count,FILE * stream );

返回值:

thetotalnumberofelementssuccessfullyreadisreturned。

ifthisnumberdiffersfromthecountparameter,eitherareadingerroroccurredortheend-of-filewasreachedwhilereading.inbothcases

If either size or count is zero,thefunction returnszeroandboththestreamstateandthecontentpointedbyptrremainunchanged。

size_t is an unsigned integral type。

#includeint main () {

file*FP=fopen('./test.txt ',' r ' );

if(FP==null ) {

打印故障(n );

}else{

打印机(fopen success (n ) );

}

char buf[1024]={0};

fread(buf,1,4,fp );

printf(%s(n )、buf ); //结果buf的内容是fp指向的文件的内容

流量(FP );

返回0;

}

fwrite:文件的写入函数是将内存中的数据写入磁盘。

函数的使用与fread类似,所以不再介绍

#includeint main () {

file*FP=fopen('./test.txt ',' r ' );

if(FP==null ) {

打印故障(n );

}else{

打印机(fopen success (n ) );

}

char buf[1024]=“haha”;

fwrite(buf、1、4、fp );

printf(%s(n )、buf ); //结果fp指向的文件内容是buf的内容

流量(FP );

返回0;

}

还有文件的操作函数。 例如fgetc、fputc、fscanf、fprintf、sscanf、ssprintf…。

特别是sscanf和sprintf提供整数和字符串的转换。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。