Added file reading capability.
This commit is contained in:
@@ -19,7 +19,8 @@ typedef uint_least8_t strlen_t;
|
||||
* than 255 characters, the string shall be truncated to make room for the null
|
||||
* byte.
|
||||
*/
|
||||
typedef struct NAME_STR {
|
||||
typedef struct NAME_STR
|
||||
{
|
||||
char *c_str;
|
||||
strlen_t len;
|
||||
} string;
|
||||
|
||||
78
src/main.c
78
src/main.c
@@ -52,7 +52,7 @@ void print_vector(string_vector *vector)
|
||||
{
|
||||
for(uint32 index = 0; index < vector->size; index++)
|
||||
{
|
||||
printf("%s", vector->array[index]->c_str);
|
||||
printf("%s\n", vector->array[index]->c_str);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,34 +84,70 @@ void perform_length_alphabet_sort(string_vector *vector)
|
||||
qsort((void *) vector->array, vector->size, sizeof(string *), compare);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
char *read_line(FILE *file, int *eof_reached)
|
||||
{
|
||||
char *tests[10] = {
|
||||
"What ",
|
||||
"Where",
|
||||
" When",
|
||||
" Why ",
|
||||
"How",
|
||||
"Test1",
|
||||
"Test2",
|
||||
"Anne",
|
||||
"Jill",
|
||||
"Bob"
|
||||
};
|
||||
char *lineBuffer = malloc(sizeof(char) * MAX_STR_SIZE + 1);
|
||||
|
||||
string_vector *vector = create_vector(0);
|
||||
|
||||
for(uint32 index = 0; index < 10; index++)
|
||||
int ch = getc(file);
|
||||
int count = 0;
|
||||
while((ch != '\n') && (ch != EOF))
|
||||
{
|
||||
string *str = create_from_cstr(tests[index]);
|
||||
if(count == MAX_STR_SIZE)
|
||||
{
|
||||
fprintf(stderr,
|
||||
"Encounted name that is too long. Max name length is %d!\n",
|
||||
MAX_STR_SIZE);
|
||||
exit(2);
|
||||
}
|
||||
lineBuffer[count] = (char)ch;
|
||||
count++;
|
||||
ch = getc(file);
|
||||
}
|
||||
if(ch == EOF)
|
||||
{
|
||||
*eof_reached = 1;
|
||||
}
|
||||
lineBuffer[count] = '\0';
|
||||
return lineBuffer;
|
||||
}
|
||||
|
||||
void read_file_into_vector(FILE *file, string_vector *vector)
|
||||
{
|
||||
if(!file || !vector)
|
||||
{
|
||||
fprintf(stderr, "Invalid File Or Memory Error\n");
|
||||
return;
|
||||
}
|
||||
int eof_reached = 0;
|
||||
while(!eof_reached)
|
||||
{
|
||||
char *line = read_line(file, &eof_reached);
|
||||
string *str = create_from_cstr(line);
|
||||
free(line);
|
||||
|
||||
strip(str);
|
||||
if(str->len == 0)
|
||||
{
|
||||
destroy_string(str);
|
||||
continue;
|
||||
}
|
||||
vector_add(vector, str);
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
if(argc < 2)
|
||||
{
|
||||
fprintf(stderr, "Usage: name_sort <input_file>\n");
|
||||
return 1;
|
||||
}
|
||||
FILE *file = fopen(argv[1], "r");
|
||||
|
||||
string_vector *vector = create_vector(0);
|
||||
read_file_into_vector(file, vector);
|
||||
|
||||
print_vector(vector);
|
||||
perform_length_alphabet_sort(vector);
|
||||
printf("\nSorted Array\n------------\n");
|
||||
print_vector(vector);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user