C语言读取文件内容到数组的代码
转自:http://blog.csdn.net/aaa20090987/article/details/8447658
#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; } //在数组末尾加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; }