第5章 Linux文件系统与设备文件之二(Linux文件操作C库文件)

5.1.2 C库文件操作

C库函数的文件操作独立于具体的操作系统平台,不管是在DOS、Windows、Linux还是在VxWorks中都是这些函数:

1.创建和打开

FILE *fopen(const char *path, const char *mode);

fopen()用于打开指定文件filename,其中的mode为打开模式,C库函数中支持的打开模式如表5.3所示。

表5.3 C库函数文件打开标志

第5章 Linux文件系统与设备文件之二(Linux文件操作C库文件)

2.读写

C库函数支持以字符、字符串等为单位,支持按照某种格式进行文件的读写,这一组函数为:

int fgetc(FILE*stream);
int fputc(int c, FILE*stream);
char *fgets(char *s, int n, FILE*stream);
int fputs(const char *s, FILE*stream);
int fprintf(FILE*stream, const char *format, ...);
int fscanf (FILE*stream, const char *format, ...);
size_t fread(void *ptr, size_t size, size_t n, FILE*stream);

size_t fwrite (const void *ptr, size_t size, size_t n, FILE*stream);

fread()实现从流(stream)中读取n个字段,每个字段为size字节,并将读取的字段放入ptr所指的字符数组中,返回实际已读取的字段数。当读取的字段数小于n时,可能是在函数调用时出现了错误,也可能是读到了文件的结尾。因此要通过调用feof()和ferror()来判断。

fwrite ()实现从缓冲区ptr所指的数组中把n个字段写到流(stream)中,每个字段长为size个字节,返

回实际写入的字段数。

另外,C库函数还提供了读写过程中的定位能力,这些函数包括:

int fgetpos(FILE*stream, fpos_t *pos);

int fsetpos(FILE*stream, const fpos_t *pos);

int fseek(FILE*stream, long offset, int whence);

3.关闭
利用C库函数关闭文件是很简单的操作:

int fclose (FILE*stream);

代码清单5.2 Linux文件操作用户空间编程(使用C库函数)

#include <stdio.h>


#define LENGTH 100

void main()
{
    FILE *fd;
    char str[LENGTH];
 
    fd = fopen("hello.txt", "w+");/* 创建并打开文件 */
    if (fd) {
       fputs("Hello World", fd); /* 写入字符串 */
       fclose(fd);
    }

   fd = fopen("hello.txt", "r");
   fgets(str, LENGTH, fd);       /* 读取文件内容 */
   printf("%s\n", str);
   fclose(fd);
}