歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux下調用庫函數實現文件的讀寫

Linux下調用庫函數實現文件的讀寫

日期:2017/3/1 9:47:06   编辑: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:打開模式

實例代碼

[email protected]:/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 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 }

[email protected]:/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]
[email protected]:/home/linuxidc/桌面/c++# ./file_lib_copy file_lib_copy.cpp test2.c
form file size is=1030
[email protected]:/home/linuxidc/桌面/c++#

Copyright © Linux教程網 All Rights Reserved