linux c之用fopen、fputs、fgets、 fseek来对文件进行写、替换、读

来源:互联网 发布:百度算法调整2017 编辑:程序博客网 时间:2024/05/16 06:07

1、函数说明

1、fgets

#include        char *fgets(char *s, int size, FILE *stream);


功能:从文件流读取一行,送到缓冲区,使用时注意以下几点:
        返回值:成功时s指向哪返回的指针就指向哪,出错或者读到文件末尾时返回NULL

2、fputs

#includeint fputs(const char *s, FILE *stream);        int puts(const char *s);


返回值:成功返回一个非负整数,出错返回EOF

fputs向指定的文件写入一个字符串,puts向标准输出写入一个字符串。

3、fseek

头文件:#include <stdio.h>定义函数:int fseek(FILE * stream, long offset, int whence);


函数说明:
fseek()用来移动文件流的读写位置.

1、参数stream 为已打开的文件指针,
2、参数offset 为根据参数whence 来移动读写位置的位移数。参数 whence 为下列其中一种:
    SEEK_SET 从距文件开头offset 位移量为新的读写位置. SEEK_CUR 以目前的读写位置往后增加offset 个位移量.
    SEEK_END 将读写位置指向文件尾后再增加offset 个位移量. 当whence 值为SEEK_CUR 或
    SEEK_END 时, 参数offset 允许负值的出现.

下列是较特别的使用方式:
1) 欲将读写位置移动到文件开头时:fseek(FILE *stream, 0, SEEK_SET);
2) 欲将读写位置移动到文件尾时:fseek(FILE *stream, 0, 0SEEK_END);


2、文件读、写、替换代码实现

#include <stdio.h>#define PATH  "example.txt"int main (){  FILE * pFile;  pFile = fopen (PATH, "w" );//创建一个只读的example.txt  fputs ( "This is an apple." , pFile );//写入This is an apple.到example.txt   fseek ( pFile , 9 , SEEK_SET ); //设置文件内部位置指针从文件的开始处偏移9个字节  fputs ( " sam" , pFile ); //在新的文件内部指针处写下sam,  //即将This is an apple.变成This is an sample.  fclose ( pFile );  pFile = fopen(PATH, "r");  char data[100];  while((fgets(data,1024,pFile))!=NULL) {         printf("%s", data);  }  return 0;}~                                                                                                                                                                                                           ~                                                                                                                                                                                                           ~                                                                                                                                                                                                           ~            


3、结果展示


0 0