c语言对文件打开并显示内容
#include"stdafx.h"#include<stdio.h>#include<conio.h>#include<stdlib.h>#include<string...
#include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
long getFileSize(char *path)
{FILE *fp;long iBytes;
fp=fopen(path,"rb");
if(fp==0) return -1;//假如打开失败则返回值-1
fseek(fp,0l,SEEK_END);
iBytes=ftell(fp);
fclose(fp);
return iBytes;
}
unsigned char *readFile(char *path)
{unsigned char *pBuffer;
FILE *fp;
long iBytes;
iBytes=getFileSize(path);
if(iBytes<0) return NULL;
fp=fopen(path,"rb");
pBuffer=(unsigned char *)malloc(iBytes);
fread(pBuffer,1,iBytes,fp);
fclose(fp);
return pBuffer;
}
void main()
{char path[1024];
unsigned char *pBuffer;
printf("Please input the file path!\n");
gets(path);
pBuffer=readFile(path);
if(pBuffer==NULL) printf("文件打开失败~~");
printf("%s",pBuffer);
getch();
}文件是可以打开,但是尾巴有乱码~~ 展开
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
long getFileSize(char *path)
{FILE *fp;long iBytes;
fp=fopen(path,"rb");
if(fp==0) return -1;//假如打开失败则返回值-1
fseek(fp,0l,SEEK_END);
iBytes=ftell(fp);
fclose(fp);
return iBytes;
}
unsigned char *readFile(char *path)
{unsigned char *pBuffer;
FILE *fp;
long iBytes;
iBytes=getFileSize(path);
if(iBytes<0) return NULL;
fp=fopen(path,"rb");
pBuffer=(unsigned char *)malloc(iBytes);
fread(pBuffer,1,iBytes,fp);
fclose(fp);
return pBuffer;
}
void main()
{char path[1024];
unsigned char *pBuffer;
printf("Please input the file path!\n");
gets(path);
pBuffer=readFile(path);
if(pBuffer==NULL) printf("文件打开失败~~");
printf("%s",pBuffer);
getch();
}文件是可以打开,但是尾巴有乱码~~ 展开
1个回答
展开全部
追问
有没有不用加结束码的吗?我的老师原本写了pBuffer=(unsigned char *)malloc(iBytes+1);
fread(pBuffer,1,iBytes,fp);
pBuffer[iBytes]=0;
但是他加了unsigned就把结束码那条就删除了
追答
pBuffer[iBytes]=0;
这个效果 应该和 pBuffer[iBytes]=‘\0’;一样的
字符串 一定要有 \0 结束的,标志字符串结尾
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询