#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;
}
.
分享到:
相关推荐
c语言读取文件信息 c语言读取文件信息 LINUX LINUX
c语言文件操作,详细的给出了如何读取文本文件数据,以及存储数据到另外的文件中
在Windows下可以用GetPrivateProfileString或GetPrivateProfileInt方便读取.ini配置文件内容,自己尝试写了一下这个函数。还有一些bug,后面慢慢改。
该代码采用C语言编程,通过文件路径读取文本文件,并保存在数组中。
里面涵盖了关于C语言中如何从文件中读取信息 如何讲信息写入文件 包括字符的写入和读取 字符串的写入和读取以及整行读取等等的代码
用C语言实现的txt文件的读取,比如读取到文本尾如何换行,如果到指定的位置读取等。
自己亲自测试,和winhex下16进制数据对比,确实正确!
在本篇文章里小编给大家整理的是关于c语言如何读取txt文件内容,需要的朋友们可以参考下。
// C++读取文本到数组.cpp : 定义控制台应用程序的入口点。 // #include stdafx.h int readfile1D() { char a[100]; int i; FILE *fp = fopen(1.txt,r); if(fp == NULL) { printf(文件读取无效.\n); ...
用c语言编写的程序,用于读取txt文件的数据
本文档是C语言编写,基于linux下对pcap格式文件的分析,希望能够提供帮助。
C语言编程,连接数据库有点麻烦,但测试总需要数据,使用手动输入的方式固然是可行的,但是在开发过程中难免会重复使用同样的数据进行测试,而且输入测试数据的过程中花费的时间会很多,所以我们要学会变通,通过...
利用vs2005的filestream功能逐行读取文本文件,并有效地解决了由于分隔符复杂而造成的小问题。
用C语言实现BMP图像读取,显示,简单处理!通过结构体变量存储文件头信息,定义动态二维数组实现像素信息的存储!
TDMS文件读写【官方C语言例程】,亲测可用,示例只是提供源文件,需要自己新建工程来使用
精短高效的XML解析器,纯C单一程序,应用于银行的国税库行横向联网接口系统中,稳定可靠,运行速度飞快。
如果出现无法打开文件 就需要自己在代码工程的根目录下新建filename.txt并自行写入部分内容。
c++读取文件的常用方法。新建一个空白项目,把ofstream_demo.cpp文件加入进去就可以运行了。
关于C语言的文件操作PPT,其内容简短精悍,对于初学者较为适合
C语言从文本文档读取字符串(用户名和密码验证)