摘要
C實現將txt數據讀入內存/CPU緩存的函數,不多說,實現如下。
1. 實現代碼
#include "stdafx.h" #include <stdio.h> #include <stdlib.h> int filelength(FILE *fp); char *readfile(char *path); int main(void){ char *string; string=readfile("C:/Users/Joe WANG/Desktop/Data.txt"); printf("數據讀入內存完畢! /n"); printf("內存中的數據如下:/n%s /n",string); system("pause"); return 0; } char *readfile(char *path){ FILE *fp; int length; char *ch; if((fp=fopen(path,"r"))==NULL){ printf("open file %s error./n",path); exit(0); } length=filelength(fp); ch=(char *)malloc(length); fread(ch,length,1,fp); *(ch+length)='/0'; return ch; } int filelength(FILE *fp){ int num; fseek(fp,0,SEEK_END); num=ftell(fp); fseek(fp,0,SEEK_SET); return num; }
2. Data.txt中的源數據
3. 測試結果
新聞熱點
疑難解答
圖片精選