Linux 库函数文件操作
来源:互联网 发布:php 九宫格抽奖源代码 编辑:程序博客网 时间:2024/06/06 20:50
利用库函数操作文件具有跨平台的作用(库函数不随系统平台而变,即不管win还是Linux都适用),而利用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@wl-MS-7673:/home/wl/桌面/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 }
- 64
- 65
- root@wl-MS-7673:/home/wl/桌面/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@wl-MS-7673:/home/wl/桌面/c++# ./file_lib_copy file_lib_copy.cpp test2.c
- form file size is=1030
- root@wl-MS-7673:/home/wl/桌面/c++#
0 0
- linux 文件操作库函数
- Linux 库函数文件操作
- Linux 文件操作库函数 -- ioctl
- Linux 库函数实现文件操作
- Linux 文件操作库函数 – close
- linux-基础-文件操作/C-库函数文件操作/时间操作
- 库函数文件操作
- linux中c语言的扩展库函数之文件操作
- Linux C高级编程——文件操作之库函数
- 简单文件操作(库函数)
- linux 底层文件访问(库函数)
- Linux 文件访问--- C库函数
- Linux库函数方式访问文件
- 【Linux库函数编程】文件编程
- linux系统下库函数和系统调用都对文件的基本操作
- Unix/Linux环境C编程入门教程(41) C语言库函数的文件操作详解
- Linux文件操作总结(系统调用和标准IO库函数)
- linux文件操作笔记(1)——系统调用、库函数
- 链表
- ASP.NET SQL SERVER 三层架构 Ajax 分页
- Sphinx 在 Linux 下的安装与基本配置
- eclipse有时候不能离线或者在线安装SVN
- 从gff3文件获取fasta序列(2)
- Linux 库函数文件操作
- Failed to load the JNI shared
- 判断两个IP是否属于同一子网
- httpclient中PostMethod和HttpPost
- Spring Model
- 同一个tableview实现多选单选删除
- git clone error setting certificate verify locations
- 跨区域Docker Registry同步方案探索
- 带头结点的单链表的八种基本操作