Let's imagine having two text documents : input.txt and output.txt . The content of the second is empty and the content of the first is:
In some of the stain
whose name I don't want to remember
lived a hidalgo
named Don Quixote
What we want to do is copy the same text from input.txt to output.txt , but expanding the whitespace between the words on each line (without expanding the line breaks). We can assume that the length of the input.txt lines does not exceed 80 characters, counting the line break.
The input.txt file will be input as standard input, and output.txt will be standard output. The number of white spaces between words will be argv[1]. So, an example of the call would be ./program 3 < input.txt > output.txt
To solve this exercise, I propose this code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
if(argc != 2){
return 1;
}
else{
int espaciado = atoi(argv[1]);
int maxLinea = 80;
char linea[maxLinea];
char *palabra; palabra = malloc(maxLinea*sizeof(char));
char anadir[espaciado];/*Espacio en blanco que debemos anadir*/
int i = 0;
for(; i < espaciado; i++){
anadir[i] = ' ';
}
while(!feof(stdin)){
fgets(linea,maxLinea,stdin);/*Cogemos una línea*/
char delimitador[] = " ";
palabra = strtok(linea,delimitador);/*Cogemos palabra a palabra cada línea*/
while(palabra != NULL){
fputs( strcat(palabra,anadir) , stdout);
palabra = strtok(linea,delimitador);
}
}
}
return 0;
}
However, it does nothing at all . The output.txt document is left empty. What is failing?
Thanks.
The first problem we encounter is that the array
anadir
is badly initialized:In C, character strings must always end with
\0
. Functions that manipulate strings in C are based on this premise. Your string does not meet this requirement, so the call tostrcat
will cause unwanted characters to be copied into the buffer (until the program finds one\0
somewhere).On the other hand, the function
strtok
works its magic by modifying the original character string. What it does is replace the delimiter with a string terminator\0
.Later you call
strcat
and this function will add the content ofanadir
to the end oflinea
, that is, where the space was before ... and crushing whatever is beyond that space.An example to see it more clearly:
As you can see, you are losing information and it is not what you want.
Another error you have is checking for
feof
:The flag
feof
is activated after the first incorrect read, that is, the check forfeof
must be done immediately after callingfgets
, not before.I would approach the exercise in another way:
With code, it would be something like this: