Permalink
Browse files

New Solution of Task1

  • Loading branch information...
1 parent 075fb79 commit bf172740b853ac79687a9ad60dab328b95eb4e0a @andrew-iv-os committed Jan 17, 2012
Showing with 213 additions and 177 deletions.
  1. +213 −0 SortFiles/main.cpp
  2. +0 −177 SortFiles/src/SortFiles.c
View
@@ -0,0 +1,213 @@
+/*
+ * File: main.cpp
+ * Author: andrew
+ * Судя по примеру одногрупников. Решил что мне будет проще нормально переписать на C++ в ООП стиле с использованием стандартных библиотек,
+ * чем на С.
+ * Created on 16 Январь 2012 г., 14:00
+ */
+
+#include <cstdlib>
+#include <string>
+#include <algorithm>
+#include <fstream>
+#include <iostream>
+#include <cstring>
+#include <vector>
+#include <tr1/memory>
+#include <limits.h>
+#include <stdexcept>
+
+using namespace std;
+using namespace std::tr1;
+
+class NumberCollectionException : exception {
+protected:
+ string message;
+
+public:
+
+ NumberCollectionException(string msg) throw () {
+ message = msg;
+
+ }
+
+ virtual string what() {
+ return message;
+ };
+
+ virtual ~NumberCollectionException() throw () {
+ };
+};
+
+class NumberCollectionIOException : NumberCollectionException {
+public:
+
+ NumberCollectionIOException(string msg) : NumberCollectionException(msg) {
+ return;
+ };
+ virtual string what() {
+ return message;
+ };
+};
+
+class NumberReader {
+private:
+ const static int local_buffer_size = 0x1000;
+ const static int max_number_size = 0x7fffffff;
+ shared_ptr <ifstream> input_stream;
+ char char_buffer[local_buffer_size];
+
+public:
+ string error_prefix;
+
+ NumberReader(shared_ptr <ifstream> input_stream) {
+ this->input_stream = input_stream;
+ }
+
+ shared_ptr< vector<int> > get_numbers() {
+ long long cur_number = 0;
+ bool is_number_ready = false;
+ bool is_number_to_long = false;
+ int local_data_size = 0;
+ int cur_pointer = 0;
+
+ shared_ptr< vector<int> > result (new vector<int>());
+ while (true) {
+ if (cur_pointer >= local_data_size) {
+ this->input_stream->read(char_buffer, local_buffer_size);
+ local_data_size = this->input_stream->gcount();
+ if (local_data_size == 0) {
+ if (is_number_ready && cur_number <= max_number_size)
+ result->push_back(cur_number);
+ return result;
+ }
+ cur_pointer = 0;
+ };
+ if (char_buffer[cur_pointer] >= '0' && char_buffer[cur_pointer] <= '9') {
+ is_number_ready = true;
+ cur_number = cur_number * 10 + char_buffer[cur_pointer] - '0';
+ } else {
+ if (is_number_ready && cur_number <= max_number_size)
+ result->push_back(cur_number);
+ is_number_ready = false;
+ is_number_to_long = false;
+
+ }
+ cur_pointer++;
+ }
+ return result;
+ };
+};
+
+void exit_with_error(char * msg, int status = 1) {
+ cout << msg;
+ exit(status);
+}
+
+class NumberCollection {
+private:
+ vector<int> numbers;
+public:
+
+ void load_from_file(char * filename) {
+
+ shared_ptr <ifstream> _in_stream(new ifstream(filename, ifstream::in));
+ if (_in_stream->fail()) throw NumberCollectionIOException(string(string("Can't Open file: ") + filename));
+ try {
+ NumberReader nums_reader(_in_stream);
+ nums_reader.error_prefix = "eee:"; // filename+string(":");
+ shared_ptr< vector<int> > new_numbers = nums_reader.get_numbers();
+ numbers.insert(numbers.end(), new_numbers->begin(), new_numbers->end());
+
+ } catch (ifstream::failure& exc) {
+ string msg = "Problem in reading file :";
+ msg += filename;
+ throw NumberCollectionIOException(msg);
+ } catch (bad_alloc& exc) {
+ throw NumberCollectionException(string("Bad memory allocation exception in reading from file: ") + filename);
+ } catch (overflow_error& exc) {
+ throw NumberCollectionException(string("Overflow in reading from file: ") + filename);
+ } catch (exception& exc) {
+ throw NumberCollectionException(string("Unknown Exception in reading from file: ") + filename);
+ } catch (...) {
+ throw NumberCollectionException(string("Unknown Error in reading from file: ") + filename);
+ }
+
+ };
+
+ void sort_numbers() {
+ try {
+ sort(numbers.begin(), numbers.end());
+ } catch (bad_alloc& exc) {
+ throw NumberCollectionException(string("Bad memory allocation exception in sorting: "));
+ } catch (overflow_error& exc) {
+ throw NumberCollectionException(string("Overflow in sorting "));
+ } catch (exception& exc) {
+ throw NumberCollectionException(string("Unknown Exception in sorting"));
+ } catch (...) {
+ throw NumberCollectionException(string("Unknown Error in sorting"));
+ }
+ }
+
+ void print_to_stream(ostream &stream) {
+ try {
+ for (vector<int>::iterator it = numbers.begin(); it != numbers.end(); it++) {
+ stream << *it << endl;
+ }
+ } catch (...) {
+ throw NumberCollectionIOException(string("Error in printing to file"));
+ }
+ };
+};
+
+/*
+ *
+ */
+int main(int argc, char** argv) {
+ NumberCollection num_col;
+ ostream *output_stream = &cout;
+ bool read_output = false;
+ if(argc == 1)
+ {
+ cerr<<"usage: ./sortfiles [file1] ... [filen] [--output \"filename\"]\n";
+ return 0;
+ }
+
+ for (int argn = 1; argn < argc; argn++)
+ {
+ try {
+ if (strcmp(argv[argn], "--output") == 0) {
+ read_output = true;
+ } else {
+ if (read_output) {
+ output_stream = new ofstream(argv[argn], ofstream::out);
+ if (output_stream->fail()) {
+ exit_with_error("Can't open output file");
+ }
+ read_output = false;
+ } else {
+ num_col.load_from_file(argv[argn]);
+ }
+ }
+ }
+ catch (NumberCollectionIOException &exc) {
+ cerr << exc.what() << endl;
+ }
+ catch (NumberCollectionException &exc) {
+ cerr << exc.what() << endl;
+ } ;
+ }
+ try {
+ num_col.sort_numbers();
+ num_col.print_to_stream(*output_stream);
+
+ }
+ catch (NumberCollectionException &exc) {
+ cerr << exc.what() << endl;
+ };
+
+ /*if (output_stream != &cout)
+ delete output_stream;*/
+ return 0;
+}
+
@@ -1,177 +0,0 @@
-/*
- Сделал я большую часть на системных вызовах. таким образом получается лучшая взаимосвязь с системой.
- */
-#include <ctype.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <string.h>
-
-#define ARR_SIZE 0x1000000
-#define BF_SIZE ARR_SIZE*sizeof(int)
-
-u_char buffer[BF_SIZE];
-int *int_buffer;
-int int_buffer_count;
-off_t file_size;
-int uk_symb;
-int input_handle;
-char is_availible = 1;
-int read_count;
-
-inline u_char get_next_symb(u_char buffer[], int size) {
- is_availible = 1;
- if (uk_symb % size == 0) {
- read_count = read(input_handle, buffer, size);
- if (read_count == 0) {
- is_availible = 0;
- if (uk_symb != file_size) {
- fprintf(stderr, "can't read file o end");
- }
- return 0;
- }
- }
- if (uk_symb % size >= read_count) {
- is_availible = 0;
- return 0;
- }
- uk_symb++;
- return buffer[(uk_symb - 1) % size];
-
-}
-
-int compare(const void * a, const void * b) {
- return (*(int*) a - *(int*) b);
-}
-
-void array_sort(int arr[], int count) {
- qsort(arr, count, sizeof(int), compare);
- return;
-}
-
-void int_buffer_add(int val) {
- int_buffer[int_buffer_count++] = val;
-
-}
-
-void populate() {
- long long now = 0;
- int_buffer_count=0;
- uk_symb=0;
- is_availible=1;
-
- int state = 0;
- char min = 1;
- /*
- 0: deafult
- 1: - on start
- 2: число уже идёт
- 3: игнорить число
- */
- while (is_availible) {
-
- u_char symb = get_next_symb(buffer, BF_SIZE);
- if(!is_availible)
- break;
- switch (state) {
- case 0:
- now = 0;
- if (symb == '-') {
- min = -1;
- state = 1;
- } else if (symb >= '0' && symb <= '9') {
- min = 1;
- now = symb - '0';
- state = 2;
- } else {
-
- fprintf(stderr, "bad symbol %c at %d\n", symb, (int) uk_symb);
- }
- break;
- case 1:
-
- case 2:
- if (symb >= '0' && symb <= '9') {
- state = 2;
- now = now * 10 + symb - '0';
- if (now & 0xFFFF80000000) {
- fprintf(stderr,
- "value in bad range at %d\n, ignoring next digits",
- (int) uk_symb);
- now = now / 10;
- int_buffer_add(now * min);
- state = 3;
- }
- } else {
- if (state != 1)
- {
- int_buffer_add(now * min);
- state = 0;
- }
- if (!isblank(symb))
- fprintf(stderr, "bad symbol %c at %d\n", symb,
- (int) uk_symb);
- }
-
- break;
- case 3:
- if (!(symb >= '0' && symb <= '9')) {
- state = 0;
-
- }
-
- break;
- }
-
- }
-}
-
-
-
- int sortfile(char *filename) {
- struct stat st;
- uk_symb=0;
- if (stat(filename, &st) == -1) {
- fprintf(stderr, "can't stat file %s\n", filename);
-
- return EXIT_FAILURE;
- }
- file_size = st.st_size;
- input_handle = open(filename, O_RDONLY);
- int_buffer = malloc(st.st_size / 2 + 1);
- int_buffer_count=0;
- populate();
- close(input_handle);
- array_sort(int_buffer,int_buffer_count);
- int i;
- char *new_name=malloc(strlen(filename)+10);
- sprintf(new_name,"%s.sorted",filename);
- FILE* out;
- if(out=fopen(new_name,"wt"))
- {
- for(i=0;i<int_buffer_count;i++)
- if(fprintf(out,"%d\n",int_buffer[i])<0)
- fprintf(stderr, "can't write to file\n");
- fclose(out);
- }
- free(int_buffer);
- free(new_name);
-
- /*u_char *barray=malloc(st.st_size);
- int *iarray = malloc();*/
-
- return 0;
- }
-
-int main(int argc, char **argv) {
-
- int i;
- for (i = 1; i < argc; i++) {
- sortfile(argv[i]);
- }
- return 0;
- };

0 comments on commit bf17274

Please sign in to comment.