Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- char* get_word(FILE* input);
- void input_free (char **buffer, int size);
- int main(int argc, char *argv[]) {
- FILE *input, *output;
- char *temp;
- char **buffer = NULL;
- int i;
- int size = 0;
- int status;
- if (argc != 3) {
- printf ("Invalid number of parameters\n");
- exit (1);
- }
- /* Odczyt */
- input = fopen(argv[1], "r");
- if(input == NULL) {
- printf("Error. Cannot open input file.\n");
- exit (1);
- }
- while (1) {
- temp = get_word (input);
- if (temp == NULL) break;
- if (buffer == NULL) {
- size++;
- buffer = (char **)malloc (sizeof(char *));
- }
- else {
- size++;
- buffer = (char **)realloc (buffer, size * sizeof(char *));
- }
- buffer[size-1] = temp;
- }
- fclose (input);
- printf("\n");
- for (i=0; i<size; i++) {
- printf("%s",buffer[i]);
- }
- printf("\n");
- /* Zapis */
- output = fopen (argv[2], "w");
- if (output == NULL) {
- printf ("Cannot open output file\n");
- input_free (buffer, size);
- exit (1);
- }
- for (i=0; i<size; i++) {
- status = fputs (buffer[i], output);
- if (status == EOF) {
- printf ("Error while writing to a output file\n");
- input_free (buffer, size);
- exit (1);
- }
- }
- fclose (output);
- /* Dealokacja */
- input_free (buffer, size);
- return 0;
- }
- char *get_word (FILE* input) {
- char *word = NULL;
- int temp;
- int size = 0;
- while (1) {
- temp = fgetc (input);
- if (temp == EOF) {
- if (word == NULL) return NULL;
- else break;
- }
- size++;
- if (word == NULL) {
- word = malloc (sizeof(char));
- word[0] = (char)temp;
- }
- else {
- word = (char *)realloc ((void *)word, (size_t) size);
- word[size-1] = (char)temp;
- }
- if ((temp == '\n')||(temp == ' ')||(temp == '\t')) break;
- }
- word = (char *)realloc ((void *)word, (size_t) (size+1));
- word[size] = '\0';
- return word;
- }
- void input_free (char **buffer, int size) {
- int i;
- for (i=0; i<size; i++) {
- free (buffer[i]);
- buffer[i] = NULL;
- }
- free (buffer);
- buffer = NULL;
- }
Add Comment
Please, Sign In to add comment