File test.c

De la WikiLabs
Jump to navigationJump to search
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stack.h"

#define INPUT_FILE_NAME "files/word.in"
#define OUTPUT_FILE_NAME "files/word.out"

#define MAX_WORD_LENGTH 30


/**
 * This function opens a file specified by the file_name and reads 
 * a word which is returned.
 */
char* read_word_from_file(char* file_name){
    FILE *input_file;
    input_file = fopen(file_name, "r");
    if(input_file == NULL){
        printf("The file %s couldn't be opened!\n", file_name);
        return NULL;
    }
    
    char *word = (char*)malloc(MAX_WORD_LENGTH * sizeof(char));
    fscanf(input_file, "%s", word);
    
    fclose(input_file);
    return word;
}

/**
 * This function writes a word to a specified file.
 */
void write_word_to_file(char* file_name, char* word){
    FILE *output_file;
    output_file = fopen(file_name, "w");
    if(output_file == NULL){
        printf("The file %s couldn't be opened!\n", file_name);
        return;
    }
    
    fprintf(output_file, "%s\n", word);
    
    fclose(output_file);
}

char* reverse_word(char* word){
    int i;
    struct stack * letter_stack = create_stack(MAX_WORD_LENGTH);
    
    for(i=0; i<strlen(word); i++){
        stack_push(letter_stack, word[i]);
    }
    
    i=0;
    while(!is_empty(letter_stack)){
        word[i] = stack_pop(letter_stack);
        i++;
    }
    return word;
}

int main(){
    
    char* word = read_word_from_file(INPUT_FILE_NAME);
    printf("The word is %s\n", word);
    
    word = reverse_word(word);
    
    write_word_to_file(OUTPUT_FILE_NAME, word);
    
    free(word);
    
    return 0;
}