Linux下调用库函数实现文件的读写


1. Linux系统调用,文件的描述符使用的是一个整数,库函数访问文件使用FILE类型的指针去指向描述文件;

2. 库函数不随系统平台而变,即不管win还是Linux都适用;

库函数 - 读文件

size_t fread(void *ptr, size_t size, size_t n, FILE *stream)

功能:从stream指向的文件中读取n个字段,每个字段为size字节,并将读取的数据放入ptr所指向的字符数组中,返回实际已读取的字节数。(读出来的数据量为size*n)

库函数 - 写文件

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

功能:从缓冲区ptr所指向的数组中把n个字段写到stream指向的文件中,每个字段长为size个字节,返回实际写入的字段数。

库函数 - 创建和打开

FILE *fopen(const char *filename, const char *mode)

filename:打开的文件名(包含路径,缺省为当前路径)

mode:打开模式

实例代码

root@www.bkjia.com:/home/bkjia/桌面/c++# cat -n file_lib_copy.cpp
    1 
    2 #include <stdio.h>
    3 #include <string.h>
    4 #include <stdlib.h>
    5 #define BUFFER_SIZE 1024
    6 
    7 /*
    8  * 程序入口
    9  * */
    10 int main(int argc,char **argv)
    11 {
    12  FILE *from_fd;
    13  FILE *to_fd;
    14  long file_len=0;
    15  char buffer[BUFFER_SIZE];
    16  char *ptr;
    17 
    18 /*判断入参*/
    19 if(argc!=3)
    20 {
    21  printf("Usage:%s fromfile tofile\n",argv[0]);
    22  exit(1);
    23 }
    24 
    25 /* 打开源文件 */
    26 if((from_fd=fopen(argv[1],"rb"))==NULL)
    27 {
    28  printf("Open %s Error\n",argv[1]);
    29  exit(1);
    30 }
    31 
    32 /* 创建目的文件 */
    33 if((to_fd=fopen(argv[2],"wb"))==NULL)
    34 {
    35  printf("Open %s Error\n",argv[2]);
    36  exit(1);
    37 }
    38 
    39 /*测得文件大小*/
    40 fseek(from_fd,0L,SEEK_END);
    41 file_len=ftell(from_fd);
    42 fseek(from_fd,0L,SEEK_SET);
    43 printf("form file size is=%d\n",file_len);
    44 
    45 /*进行文件拷贝*/
    46 while(!feof(from_fd))
    47 {
    48  fread(buffer,BUFFER_SIZE,1,from_fd);
    49  if(BUFFER_SIZE>=file_len)
    50  {
    51   fwrite(buffer,file_len,1,to_fd);
    52  }
    53  else
    54  {
    55   fwrite(buffer,BUFFER_SIZE,1,to_fd);
    56   file_len=file_len-BUFFER_SIZE;
    57  }
    58  bzero(buffer,BUFFER_SIZE);
    59 }
    60 fclose(from_fd);
    61 fclose(to_fd);
    62 exit(0);
    63 }

root@www.bkjia.com:/home/bkjia/桌面/c++# g++ file_lib_copy.cpp -o file_lib_copy
file_lib_copy.cpp: 在函数‘int main(int, char**)’中:
file_lib_copy.cpp:43:41: 警告: 格式 ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat]
root@www.bkjia.com:/home/bkjia/桌面/c++# ./file_lib_copy file_lib_copy.cpp test2.c
form file size is=1030
root@www.bkjia.com:/home/bkjia/桌面/c++#

相关内容

    暂无相关文章