linux下調用庫函數實現檔案的讀寫

來源:互聯網
上載者:User

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@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 * */    10int main(int argc,char **argv)    11{    12FILE *from_fd;    13FILE *to_fd;    14long file_len=0;    15char buffer[BUFFER_SIZE];    16char *ptr;    17    18/*判斷入參*/    19if(argc!=3)    20{    21printf("Usage:%s fromfile tofile\n",argv[0]);    22exit(1);    23}     24    25/* 開啟源檔案 */     26if((from_fd=fopen(argv[1],"rb"))==NULL)     27{     28printf("Open %s Error\n",argv[1]);     29exit(1);     30}     31    32/* 建立目的檔案 */     33if((to_fd=fopen(argv[2],"wb"))==NULL)     34{     35printf("Open %s Error\n",argv[2]);     36exit(1);     37}     38    39/*測得檔案大小*/    40fseek(from_fd,0L,SEEK_END);    41file_len=ftell(from_fd);    42fseek(from_fd,0L,SEEK_SET);    43printf("form file size is=%d\n",file_len);    44    45/*進行檔案拷貝*/    46while(!feof(from_fd))     47{     48fread(buffer,BUFFER_SIZE,1,from_fd);    49if(BUFFER_SIZE>=file_len)    50{    51fwrite(buffer,file_len,1,to_fd);    52}    53else     54{    55fwrite(buffer,BUFFER_SIZE,1,to_fd);    56file_len=file_len-BUFFER_SIZE;    57}    58bzero(buffer,BUFFER_SIZE);    59}     60fclose(from_fd);     61fclose(to_fd);     62exit(0);     63}     64    65root@wl-MS-7673:/home/wl/案頭/c++# g++ file_lib_copy.cpp -o file_lib_copyfile_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.cform file size is=1030root@wl-MS-7673:/home/wl/案頭/c++# 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.