Linux下标准C库打开创建文件读写光标移动

178 阅读4分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

Linux下标准C库打开创建文件读写光标移动

通过man 手册查阅函数原型:

fopen函数原型:

NAME fopen, fdopen, freopen - stream open functions

SYNOPSIS #include <stdio.h>

   FILE *fopen(const char *pathname, const char *mode);
​
   FILE *fdopen(int fd, const char *mode);
​
   FILE *freopen(const char *pathname, const char *mode, FILE *stream);

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

   fdopen(): _POSIX_C_SOURCE

DESCRIPTION The fopen() function opens the file whose name is the string pointed to by pathname and associates a stream with it.

   The argument mode points to a string beginning  with  one  of  the  following sequences (possibly followed by additional characters, as described below):
​
   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 for appending (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.
​
    The mode string can also include the letter 'b' either as a last character or as  a  character  between  the characters in any of the two-character strings described above.  This is strictly for compatibility  with  C89  and  has  no effect;  the 'b' is ignored on all POSIX conforming systems, including Linux.
       (Other systems may treat text files and binary files differently, and  adding the  'b'  may  be  a good idea if you do I/O to a binary file and expect that your program may be ported to non-UNIX environments.)

fread与fwrite函数原型:

NAME fread, fwrite - binary stream input/output

SYNOPSIS #include <stdio.h>

   size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
​
   size_t fwrite(const void *ptr, size_t size, size_t nmemb,
                 FILE *stream);

DESCRIPTION The function fread() reads nmemb items of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.

   The function fwrite() writes nmemb items of data, each size  bytes  long,  to the  stream  pointed  to by stream, obtaining them from the location given by ptr.
​
   For nonlocking counterparts, see unlocked_stdio(3).

RETURN VALUE On success, fread() and fwrite() return the number of items read or written. This number equals the number of bytes transferred only when size is 1. If an error occurs, or the end of the file is reached, the return value is a short item count (or zero).

   fread()  does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred.

fseek函数原型:

NAME fgetpos, fseek, fsetpos, ftell, rewind - reposition a stream

SYNOPSIS #include <stdio.h>

   int fseek(FILE *stream, long offset, int whence);
​
   long ftell(FILE *stream);
​
   void rewind(FILE *stream);
​
   int fgetpos(FILE *stream, fpos_t *pos);
​
   int fsetpos(FILE *stream, const fpos_t *pos);

DESCRIPTION The fseek() function sets the file position indicator for the stream pointed to by stream. The new position, measured in bytes, is obtained by adding offset bytes to the position specified by whence. If whence is set to SEEK_SET, SEEK_CUR, or SEEK_END, the offset is relative to the start of the file, the current position indicator, or end-of-file, respectively. A successful call to the fseek() function clears the end-of-file indicator for the stream and undoes any effects of the ungetc(3) function on the same stream.

   The ftell() function obtains the current value of the file position indicator for the stream pointed to by stream.
​
   The rewind() function sets the file position indicator for the stream pointed to by stream to the beginning of the file.  It is equivalent to:
​
     (void) fseek(stream, 0L, SEEK_SET) except  that  the  error indicator for the stream is also cleared (see clearerr(3)).

RETURN VALUE The rewind() function returns no value. Upon successful completion, fgetpos(), fseek(), fsetpos() return 0, and ftell() returns the current offset. Otherwise, -1 is returned and errno is set to indicate the error.

代码如下所示:

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>int main()
{
        FILE *fp;
        char *str = "I Love you the way you are!\n";
        char readBuf[128]={0};
        //FILE *fopen(const char *pathname,const char *mode);
        fp=fopen("./Test1.txt","w+");
        //size_t fwrite(const void *ptr,size_t size,size_t nmemb,FILE *stream);
        //
        fwrite(str,sizeof(char),strlen(str),fp);
        //表示要写的字符串,一次写入一个字符,写入strlen个
        //fwrite(str,sizeof(char)*strlen(str),1,fp);
        //一次写入全部的,写入一次
        fseek(fp,0,SEEK_SET);
        //将光标移到开始位置
        //size_t fread(void *ptr,size_t size,size_t nmemb,FILE *stream);
        fread(readBuf,sizeof(char),strlen(str),fp);
        //fread(readBuf,sizeof(char)*strlen(str),1,fp);
        printf("read data: %s\n",readBuf);
​
        return 0;
}

fopen 的mode打开模式:

r 只读方式打开一个文本文件

rb 只读方式打开一个二进制文件

w 只写方式打开一个文本文件

wb 只写方式打开一个二进制文件

a 追加方式打开一个文本文件

ab 追加方式打开一个二进制文件

r+ 可读可写方式打开一个文本文件

rb+ 可读可写方式创建一个二进制文件

w+ 可读可写方式创建一个文本文件

wb+ 可读可写方式生成一个二进制文件

a+ 可读可写追加方式打开一个文本文件

ab+ 可读可写方式追加一个二进制文件