I'm trying to read a file and a lines next line, to see if it starts with a space, for instance:
First line
second line
Third line
fourth line
Where when I'm reading the file in, I want to check and see if the following line, has a space, if it does, I want to strcat the two lines (in this case the first and second line).
So for the first example:
1.) Read in the first line, read ahead to the second, see that their is a space, and strcat both strings, making "First linesecond line"
(Repeat for any other lines that follow this pattern).
Here's my go at it:
int main(void) {
FILE * file = fopen("file.txt","r");
if(file==NULL) { return 0; }
char * fileBuffer = malloc(sizeof(char)*100);
char * temp = malloc(sizeof(char)*100);
while(fgets(fileBuffer,100,file) != NULL) {
if(isspace(fileBuffer[0])) {
strcpy(temp,fileBuffer);
//store line that has a space in static temporary variable
}
else {
if(strcmp(temp,"") != 0) { //if temp is not empty
strcat(fileBuffer,temp);
}
}
}
free(fileBuffer);
free(temp);
return 0;
}
However this doesn't work. What happens is when fgets gets executed, it reads the first line, it sees there is no white space, and then goes to the next line, sees there is white space, stores it, but now fileBuffer doesn't contain the first line anymore, but the second.
So when I strcat the next time,I don't get the right result of "First linesecond line".
Instead i get the result of the third line mixed with the second, which is not what I want.
I'm not exactly sure how to fix my logic here, any ideas?