歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 用C語言將文件內容讀入數組

用C語言將文件內容讀入數組

日期:2017/3/1 10:03:16   编辑:Linux編程

用C語言將文件內容讀入數組,功能很常用,代碼很簡單,就不多作解釋了,直接上代碼。

#include <stdio.h>
#include <string.h>

#define MAXLEN 10240

//讀取文件filename的內容到dest數組,最多可以讀maxlen個字節
//成功返回文件的字節數,失敗返回-1
int read_file(const char *filename, char *dest, int maxlen)
{
FILE *file;
int pos, temp, i;

//打開文件
file = fopen(filename, "r");
if( NULL == file )
{
fprintf(stderr, "open %s error\n", filename);
return -1;
}

pos = 0;
//循環讀取文件中的內容
for(i=0; i<MAXLEN-1; i++)
{
temp = fgetc(file);
if( EOF == temp )
break;
dest[pos++] = temp;
}
//關閉文件
fclose(file);
//在數組末尾加0
dest[pos] = 0;

return pos;
}


int main(int argc, char **argv)
{
if( argc != 2 )
{
fprintf(stderr, "Using: ./read <filename>\n");
return -1;
}

char buffer[MAXLEN];
int len = read_file(argv[1], buffer, MAXLEN);

//輸出文件內容
printf("len: %d\ncontent: \n%s\n", len, buffer);

return 0;
}

Copyright © Linux教程網 All Rights Reserved