If you're reading a list of integers separated by commas, it would be easier to treat them as separate entities than as a string. This way you can more easily work with them. Here is an ugly way to do that, you may modify it to suit your own needs:
Code:
#include <stdio.h>
#include <stdlib.h>
int main ( void )
{
FILE *io;
int file[BUFSIZ];
int i, j;
int new_item;
io = fopen ( "input.txt", "r" );
if ( io == NULL ) {
perror ( "File open failure" );
return EXIT_FAILURE;
}
i = 0;
while ( fscanf ( io, "%d%*c", &file[i] ) == 1 )
i++;
fclose ( io );
printf ( "Enter a new item: " );
fflush ( stdout );
if ( scanf ( " %d", &new_item ) != 1 ) {
fprintf ( stderr, "Invalid input" );
return EXIT_FAILURE;
}
io = fopen ( "input.txt", "w" );
if ( io == NULL ) {
perror ( "File open failure" );
return EXIT_FAILURE;
}
for ( j = 0; j < i && file[j] <= new_item; j++ ) {
fprintf ( io, "%d,", file[j] );
printf ( "%d,", file[j] );
}
fprintf ( io, "%d,", new_item );
printf ( "%d,", new_item );
for ( ; j < i; j++ ) {
fprintf ( io, "%d,", file[j] );
printf ( "%d,", file[j] );
}
fclose ( io );
return EXIT_SUCCESS;
}