Hi everyone,
I am trying to write a little program that takes a line of comma-separated data from stdin, and insert a new entry inside it. Unfortunately it always segfaults when reading the last entry and I can't figure out why. Here's my code; can anyone help? I'm pretty sure the line I've marked with ***** is the culprit.
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[]) {
char line[1024], tokn[1024], outline[1024];
int i, j=1;
i = atoi( argv[2] );
strcpy( outline, "" );
fgets( line, 1024, stdin );
printf( "%s,%d,%d\n", line, strlen(line), line[strlen(line)]=='\0' ); //make sure "line" is a proper, \0 terminated string, which it is
if( i<=1 ) {
printf( "%s,%s", argv[1], line ); //Case when we have to put the desired string at the front
return 0;
}
strcpy( tokn, strtok( line, ",\0" ) );
while( 1 ) {
if( i==j ) {strcat( outline, argv[1] ); //have to put the string here
strcat( outline, "," ); //append comma
}
strcat( outline, tokn ); //output token from original string
strcat( outline, "," ); //append comma
strcpy( tokn, strtok( NULL, ",\0" ) ); //get next token *****
if(!tokn) break; //break from while loop if end of string is reached
printf( "%s\n", outline );
fflush(stdout);
j++;
}
if( i>j ) {
strcat( outline, argv[1] ); //Case when we have to put the desired string at the end
strcat( outline, "," );
}
outline[strlen(outline)-1] = '\0'; //remove trailing comma
printf( "%s\n", outline );
return 0;
}