#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
bool less_str(const string &fst, const string &snd)
{
return fst.length() < snd.length();
}
int main()
{
const int LENGTH = 80;
vector<string> coll;
vector<string>::iterator pos;
// Имя файла
char input[LENGTH];
string str;
FILE *fp;
const char *filename = "test.txt";
try
{
// Читаем содержимое файла в коллекцию
fp = fopen(filename, "r");
while(!feof(fp))
{
// Читаем строку из файла-источника
if(fgets(input, LENGTH, fp))
{
cout << input << endl;
str = input;
coll.push_back(str);
}
}
fclose(fp);
// Сортируем коллекцию
sort(coll.begin(), coll.end(), less_str);
// Перезаписываем файл новыми значениями
fp = fopen(filename, "w");
for(pos = coll.begin(); pos != coll.end(); ++pos)
{
fputs((*pos).c_str(), fp);
}
fclose(fp);
}
catch(bad_alloc)
{
cout << "Не удалось выделить память под коллекцию\n";
}
return 0;
} |