Hello everyone,
I am working an an example in the book I am studying and the question is:
Write a program to copy a file, expanding all tabs to multiple spaces.
I have a text file in my directory called 14E02_in.txt that has two lines:
This is the first line to text. (spaces are actually tabs)
This is the second line of text. (spaces are actually tabs)
In trying to figure this out, I did some googling and came across someone else trying to do something similar. The advice that was given explained that a '\t' in memory is stored as 1 byte and expanding the tab to 8 spaces would take up 8 bytes, so instead of trying to operate in memory, he suggested:
This is exactly what I am trying to accomplish in my program, instead of reading from stdin and writing to stdout I am reading from in_file and writing to out_file. Here is the code I've come up with so far:My suggestion: Rather than trying to operate in place (or trying to operate in memory, even) I would suggest writing this as a filter -- reading from stdin and writing to stdout one character at a time; that way you don't need to worry about memory allocation or deallocation....
This works, but as you can see, it is replacing the tabs with only one space. I know I can't declare:Code:#include <stdio.h> int main(void) { char in_name[] = "14E02_in.txt"; char out_name[] = "14E02_out.txt"; char space_str[] = " "; // 8 spaces FILE *in_file; FILE *out_file; int ch1; // used for fgetc in_file = fopen(in_name, "r"); if (in_file == NULL) { fprintf(stderr, "Error: Unable to open %s\n", in_name); exit (8); } out_file = fopen(out_name, "w"); if (out_file == NULL) { fprintf(stderr, "Error: Unable to write to %s\n", out_name); exit (8); } while (1) { ch1 = fgetc(in_file); if (ch1 == '\t') ch1 = ' '; if (ch1 == EOF) break; fputc(ch1, out_file); } fclose(in_file); fclose(out_file); return 0; }
because I will get an error trying to assign a string value to an int. There's something eluding me and any help pointing me in the right direction would be appreciated.Code:if (ch1 == '\t') ch1 = " ";