读取文件的内容,然后将文件的内容返回给一个char*类型
//读取文件的内容,然后将文件的内容返回给一个char*类型
#include<stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include<string.h>
char* file2str(const char *pathname)
{
int fd;
if(fd=open(pathname,O_RDONLY)==-1)
{ perror(pathname);
return NULL;}
char *buf=NULL;
size_t count=0,n;//count:real number
// int n=512;
do
{
buf=realloc(buf,count+512);
n=read(fd,buf+count,512);//each 512
if(n<0)
{
free(buf);
buf= NULL;
}
count+=n;
}while(n==512);
close(fd);
if(buf)
buf[count]='\0';
return buf;
}
int
main(void)
{
char *ch;
ch=file2str("/etc/passwd");//
if(!ch)
printf("can't obtain\n");
printf("%s\n",ch);
return 0;
}
为什么上述程序无法执行成功?
编译没有错误。 linux?c
[解决办法]
file2str 函数里 if(fd=open(pathname,O_RDONLY)==-1)这句代码把fd=open(pathname,O_RDONLY)放在前面执行。不然你取到的fd应该一直是0,也就是标准输入,你现在的情况应该是运行后你打什么字符就返回什么字符。你给这个赋值语句提到前面就ok了
[解决办法]
还有一种办法比较简单,直接if(fd=open(pathname,O_RDONLY)==-1) 改成if((fd=open(pathname,O_RDONLY))==-1)