#include <stdio.h>
#include <stdlib.h>
char* ReadFile(char *filename)
{
char *buffer = NULL;
int string_size,read_size;
FILE *handler = fopen(filename,"r");
if (handler)
{
//seek the last byte of the file
fseek(handler,0,SEEK_END);
//offset from the first to the last byte, or in other words, filesize
string_size = ftell (handler);
//go back to the start of the file
rewind(handler);
//allocate a string that can hold it all
buffer = (char*) malloc (sizeof(char) * (string_size + 1) );
//read it all in one operation
read_size = fread(buffer,sizeof(char),string_size,handler);
//fread doesnt set it so put a \0 in the last position
//and buffer is now officialy a string
buffer[string_size+1] = '\0';
if (string_size != read_size) {
//something went wrong, throw away the memory and set
//the buffer to NULL
free(buffer);
buffer = NULL;
}
}
return buffer;
}
int main() {
char *string = ReadFile("yourfile.txt");
if (string) {
puts(string);
free(string);
}
return 0;
}
#include <stdio.h>
long filesize(FILE *stream);
int main(void)
{
FILE *fptr;
stream = fopen( "MYFILE.TXT ", "w+ ");
fprintf(fptr, "This is a test ");
printf( "Filesize of MYFILE.TXT is %ld bytes\n ", filesize(fptr));
fclose(fptr);
return 0;
}
long filesize(FILE *fptr)
{
long curpos, length;
curpos = ftell(fptr);
fseek(fptr, 0L, SEEK_END);
length = ftell(fptr);
fseek(fptr, curpos, SEEK_SET);
return length;
}
#include "stdio.h"
int main()
{
FILE *pf=NULL; //文件指针
int filelen=0;
int i=0;
char *buf;
pf=fopen("D:\\test.txt","r"); //以只读方式打开文件
if(pf==NULL)
{
return 0;
}
else
{
//获得文件长度
fseek(pf,0,SEEK_END); //文件指针移到末尾
filelen=ftell(pf); //获得文件当前指针位置,即为文件长度
rewind(pf); //将文件指针移到开头,准备读取
buf=malloc(filelen+1); //新建缓冲区,存储独处的数据
//将缓冲区的数据设置为0
for(i=0;i<filelen+1;i++)
buf[i]=0;
//读取文件
fread(buf,filelen,1,pf);
//关闭文件
fclose(pf);
//buf中即为要读出的数据
printf("%s\n",buf); //输出一下数据,你可以随便怎么用
free(buf); //最后记得要释放
}
return 1;
}
.
1157

被折叠的 条评论
为什么被折叠?



