加入收藏 | 设为首页 | 会员中心 | 我要投稿 济南站长网 (https://www.0531zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

Linux下调用库函数达成文件的读写

发布时间:2021-11-20 17:15:13 所属栏目:教程 来源:互联网
导读:1. Linux系统调用,文件的描述符使用的是一个整数,库函数访问文件使用FILE类型的指针去指向描述文件; 2. 库函数不随系统平台而变,即不管win还是Linux都适用; 库函数 - 读文件 size_t fread(void *ptr, size_t size, size_t n, FILE *stream) 功能:从str

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.linuxidc.com:/home/linuxidc/桌面/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 tofilen",argv[0]);
    22  exit(1);
    23 }
    24
    25 /* 打开源文件 */
    26 if((from_fd=fopen(argv[1],"rb"))==NULL)
    27 {
    28  printf("Open %s Errorn",argv[1]);
    29  exit(1);
    30 }
    31
    32 /* 创建目的文件 */
    33 if((to_fd=fopen(argv[2],"wb"))==NULL)
    34 {
    35  printf("Open %s Errorn",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=%dn",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.linuxidc.com:/home/linuxidc/桌面/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.linuxidc.com:/home/linuxidc/桌面/c++# ./file_lib_copy file_lib_copy.cpp test2.c
form file size is=1030
root@www.linuxidc.com:/home/linuxidc/桌面/c++#

(编辑:济南站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读