C:返回指向内存中数据的函数
我试图编写一个函数,当调用该函数时,它读取某个日期(可以是文件或矩阵,这无关紧要),并返回指向该数据的指针。我尝试了以下代码:C:返回指向内存中数据的函数,c,pointers,malloc,C,Pointers,Malloc,我试图编写一个函数,当调用该函数时,它读取某个日期(可以是文件或矩阵,这无关紧要),并返回指向该数据的指针。我尝试了以下代码: #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/io.h> #include <sys/mman.h> #include <sys/stat.h> #i
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/io.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
char * readfile_malloc(const char *filename) {
char *f1;
struct stat s;
int fd;
int st;
off_t sz;
fd = open( filename, O_RDONLY);
st = fstat (fd, &s);
sz = s.st_size;
f1 = malloc(sz);
return (char *) memcpy(f1,&fd,sz);
}
/* Test function */
int main(int argc, const char *argv[])
{
char *rfml;
rfml = readfile_malloc("/etc/passwd");
printf ("%d\n", (int)sizeof(rfml));
printf ("%s\n", rfml);
exit(0);
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
char*readfile_malloc(常量char*filename){
char*f1;
结构统计;
int-fd;
int st;
关东施;;
fd=打开(仅文件名);
st=fstat(fd和s);
sz=s.st_尺寸;
f1=malloc(sz);
返回(char*)memcpy(f1和fd、sz);
}
/*测试功能*/
int main(int argc,const char*argv[]
{
char*rfml;
rfml=readfile_malloc(“/etc/passwd”);
printf(“%d\n”,(int)sizeof(rfml));
printf(“%s\n”,rfml);
出口(0);
}
但它不会返回我所期望的内容(/etc/passwd文件的内容)
在这种情况下,我做错了什么
干杯 如果要读取文件,需要使用
fread
。在您的代码中,memcpy
只是从文件
指针复制,而不是从文件复制。您没有在readfile\u malloc中将文件内容读取到f1中。您正在将文件描述符(fd)的地址记忆到f1中。你需要用fread阅读内容。malloc copies,嗯,内存,read
是从文件中读取内容的方法。请阅读一本C语言书。你有一些基本的误解。我读了很多;-)也许我确实遗漏了什么。回到你读过的一本书,查找“文件I/O”或“读取文件”。我想你跳过了很多页。:)fd
是一个文件描述符,它是一个句柄,您可以使用它来读取或访问使用open
打开的文件。它只是一个整数。因此memcpy(f1和fd,sz)
将文件描述符加上(可能)struct stat s,char*f1
复制到f1
点,谁知道后面是什么字节。它不复制文件内容。要获取文件内容,您需要阅读
该文件(请参见手册页的阅读
),完全同意您的观点。让我来吧。