File test.c

De la WikiLabs
Versiunea din 20 martie 2014 09:51, autor: Rhobincu (discuție | contribuții) (Pagină nouă: <syntaxhighlight lang="C"> #include <stdio.h> #include <stdlib.h> #include <string.h> #define INPUT_FILE_NAME "files/word.in" #define OUTPUT_FILE_NAME "files/word.out" #define MAX_W...)
(dif) ← Versiunea anterioară | Versiunea curentă (dif) | Versiunea următoare → (dif)
Jump to navigationJump to search
#include <stdio.h>
#include <stdlib.h>
#include <string.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){
    char stack[MAX_WORD_LENGTH];
    int stack_head = -1;
    int i;
    
    for(i=0; i<strlen(word); i++){
        stack_head++;
        stack[stack_head] = word[i];
    }
    
    i=0;
    while(stack_head >= 0){
        word[i] = stack[stack_head];
        stack_head--;
        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;
}