
下面是将文件全部读入char * buffer
/* fread example: read an entire file */
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE * pFile
long lSize
char * buffer
size_t result
pFile = fopen ( "myfile.bin" , "rb" )
if (pFile==NULL) {fputs ("File error",stderr)exit (1)}
// obtain file size:
fseek (pFile , 0 , SEEK_END)
lSize = ftell (pFile)
rewind (pFile)
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize)
if (buffer == NULL) {fputs ("Memory error",stderr)exit (2)}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile)
if (result != lSize) {fputs ("Reading error",stderr)exit (3)}
/* the whole file is now loaded in the memory buffer. */
// terminate
fclose (pFile)
free (buffer)
return 0
}
构建函数建一个string 对象,把 char * buffer 内容存入 程序部分,请自己补充:
#include <windows.h>
#include<iostream>
#include <string>
using namespace std
#include <stdio.h>
// 插入上面程序 .....
// 补充
string sss
sss.assign(buffer,result)
cout <<sss <<endl
//strfile.cpp -- read stings from a file
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
int main()
{
using namespace std
ifstream fin//定义输入文件流对象fin
fin.open("tobuy.txt") //用fin对象打开文件“tobuy.txt”
if ( fin.is_open() == false ) //打开失败则返回错误
{
cerr <<"Can't open file. Bye.\n"
exit(EXIT_FAILURE)
}
string item //定义字符串对象
int count = 0
getline(fin, item, ':') //从fin对象中向item对象中读取字符串,遇到“:”字符则完成一次读取
while(fin)//只要没读到文件尾,则循环读取并输出读取内容
{
++count
cout <<count <<": " <<item <<endl
getline(fin, item, ':')
}
cout <<"Done\n"
fin.close() //关闭文件
cin.get() //此行作用是为了让程序运行窗口能持续显示,以便观察运行效果。
return 0
}
运行效果如图:
注:tobuy.txt 的内容为:
需要注意的一点是,通过测试,可以得知:当冒号 “
:”指定为分界字符后,换行符将被视为常规字符,因此文件第一行末尾的换行符将成为包含“cottage
cheese”的字符串中的第一个字符。同样,第二行末尾的换行符是第9个输入字符串中唯一的内容。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)