如何从malloc分配的一块内存读取字符?

如何从malloc分配的一块内存读取字符?,第1张

char *p=(char *)malloc(size)

像数组那样读入和取出就可以了。

for(int i=0i<sizei++)cout<<p[i]<<endl

现成的程序, 有英文详细解释

#include <stdio.h>

#include <stdlib.h>

int main () {

FILE * pFile

long lSize

char * buffer

size_t result

pFile = fopen ( "myfile.bin" , "rb" )

if (pFile==NULL) {fputs ("File error",stderr)exit (1)}

// obtain file size: 获取文件大小

fseek (pFile , 0 , SEEK_END) //窍门 1

lSize = ftell (pFile) // 窍门 2

rewind (pFile)

// allocate memory to contain the whole file: //动态分配

buffer = (char*) malloc (sizeof(char)*lSize)

if (buffer == NULL) {fputs ("Memory error",stderr)exit (2)}

// copy the file into the buffer: // 文件复制到 缓冲变量

result = fread (buffer,1,lSize,pFile)

if (result != lSize) {fputs ("Reading error",stderr)exit (3)}

/* the whole file is now loaded in the memory buffer. */ // 整个文件在 buffer 里

// terminate

fclose (pFile) // 关闭文件

free (buffer) // 释放

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/tougao/8139011.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-13
下一篇 2023-04-13

发表评论

登录后才能评论

评论列表(0条)

保存