1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
#include <string>
#include<iostream>
using namespace std;
int filelen(string filename)
{
FILE * fp =fopen(filename.c_str(),"rt+");
fseek(fp, 0, SEEK_END);
int length =ftell(fp);
fclose(fp);
return(length);
}
void save(string filename,string content)
{
FILE * f = fopen(filename.c_str(), "wb");
int size= content.length();
fwrite(&content[0],size,1,f) ;
fclose(f);
}
void load(string filename,string &content)
{
FILE * f = fopen(filename.c_str(), "rb");
int lngth=filelen(filename);
content.resize(lngth,' ');
fread(&content[0],lngth,1,f);
fclose(f);
}
int words(string s)
{
int i,c=0;
s=s+" ";
for (i=1;i<=s.length()-1;i++)
{if ((s[i]==32 or s[i]==10 or s[i]==13) and (s[i-1] != 32 and s[i-1]!=13 and s[i-1]!=10)) c=c+1;}
return c;
}
int fileexists(string filename)
{
FILE * f = fopen(filename.c_str(), "r");
if (f){
fclose(f);
return 1;
}else{
return 0;
}
}
int main()
{
string s,ret;
s = "This is a test.\n";
s=s+"Some more text\n";
s=s+"And even more text";
cout<<"To file:"<<endl;
cout<<s<<endl<<endl;
save("Ltest.txt",s);
load("Ltest.txt",ret);
cout<<"From file:"<<endl;
cout<<ret<<endl<<endl;
cout<<"characters "<<filelen("test.txt")<<endl;
cout<<"words "<<words(ret)<<endl;
std::remove("Ltest.txt");
if (fileexists("Ltest.txt")) {cout<<"Delete the file manually"<<endl;}
else
{ cout<<"The file has been deleted"<<endl;}
cout <<"Press return to end . . ."<<endl;
cin.get();
}
|