服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C语言实现txt数据读入内存/CPU缓存实例详解

C语言实现txt数据读入内存/CPU缓存实例详解

2021-04-25 14:33jingxian C/C++

这篇文章主要介绍了C语言实现txt数据读入内存/CPU缓存实例详解的相关资料,这里对实现该函数进行了代码实现,需要的朋友可以参考下

摘要

C实现将txt数据读入内存/CPU缓存的函数,不多说,实现如下。

1. 实现代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#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中的源数据

C语言实现txt数据读入内存/CPU缓存实例详解

3. 测试结果

C语言实现txt数据读入内存/CPU缓存实例详解

延伸 · 阅读

精彩推荐