0


【Linux】回顾 C 文件接口

文章目录

在这里插入图片描述

1. 写文件

intmain(){
    FILE* fp =fopen("myfile","w");if(!fp){printf("fopen error!\n");}constchar* msg ="hello world!\n";int count =5;while(count--){fwrite(msg,strlen(msg),1, fp);}fclose(fp);return0;}

2. 读文件

#include<stdio.h>#include<string.h>intmain(){
    FILE* fp =fopen("myfile","r");if(!fp){printf("fopen error!\n");}char buf[1024];constchar* msg ="hello world!\n";while(1){// 注意返回值和参数
        ssize_t s =fread(buf,1,strlen(msg), fp);if(s >0){
            buf[s]=0;printf("%s", buf);}if(feof(fp)){break;}}fclose(fp);return0;}

3. 输出信息到显示器的几个方法

#include<stdio.h>#include<string.h>intmain(){constchar* msg ="hello fwrite\n";fwrite(msg,strlen(msg),1,stdout);printf("hello printf\n");fprintf(stdout,"hello fprintf\n");return0;}

4. stdin / stdout / stderr

  • C 默认会打开三个输入输出流,分别是 stdin, stdout, stderr
  • stdin :标准输入流,默认读取键盘的输入;
  • stdout :标准输出流,默认向显示器输出;
  • stderr :标准错误流,默认向显示器输出错误信息;
  • 仔细观察发现,这三个流的类型都是 FILE*

5. 打开文件的方式

r        Open text file for reading.
        打开文本文件进行阅读。
        The stream is positioned at the beginning of the file.
        流位于文件的开头。
    
r+         Open for reading and writing.
        打开(文件)进行阅读和写作。
        The stream is positioned at the beginning of the file.
        流位于文件的开头。
    
w         Truncate file to zero length or create text file for writing.
        将文件缩短为零长度(清空文件)或创建用于写入的文本文件。
        The stream is positioned at the beginning of the file.
        流位于文件的开头。
    
w+        Open for reading and writing.
        打开(文件)进行阅读和写作。
        The file is created if it does not exist, otherwise it is truncated.
        如果文件不存在,则创建该文件,否则将其清空。
        The stream is positioned at the beginning of the file.
        流位于文件的开头。
    
a         Open forappending(writing at end of file).
        打开用于追加(在文件末尾写入)。
        The file is created if it does not exist.
        如果文件不存在,则创建该文件。
        The stream is positioned at the end of the file.
        流位于文件的末尾。
    
a+         Open for reading and appending(writing at end of file).
        打开用于读取和追加(在文件末尾写入)。
        The file is created if it does not exist.
        如果文件不存在,则创建该文件。
        The initial file position for reading is at the beginning of the file,
        用于读取的初始文件位置是在文件的开头,
        but output is always appended to the end of the file.
        但是输出总是附加到文件的末尾。

END

标签: linux c语言

本文转载自: https://blog.csdn.net/m0_73156359/article/details/136693315
版权归原作者 字节连结 所有, 如有侵权,请联系我们删除。

“【Linux】回顾 C 文件接口”的评论:

还没有评论