Split a text file in C and give it a name -
i created code split text files when finds word "new day" , save file specific name.
first, used file_part1, file_part2 , on... however, want use first 15 characters of second line of file reading name of file saved.
for example, second line written: tam 2000-03-07t14:53... want use tam 2000-03-07
the problem function sprintf worked "%d", "%c" not working "%s" , don't have idea why.
i tried print variable before see sprintf should receiving , receiving want...
here code:
int tam_buffer = 75; int filecounter=1, linecounter=1; char fileoutputname[16]; int main(int argc, char *argv[]){ char buffer[tam_buffer]; char buffer2[15]; file *arquivo = fopen("entrada.txt", "r"); file *saida; sprintf(fileoutputname, "file_part%d.txt", filecounter); saida = fopen(fileoutputname, "w"); if(arquivo != null){ while(fgets(buffer, tam_buffer, arquivo)){ if(linecounter==2){ strncpy(buffer2,buffer,14); } if (strncmp(buffer,"newday",strlen("newday")) == 0){ fclose(saida); linecounter = 1; filecounter++; printf("%s", buffer2); sprintf(fileoutputname,"%s", buffer2); saida = fopen(fileoutputname, "w"); if (!saida) return 1; } fprintf(saida,"%s\n", buffer); linecounter++; } } fclose(saida); return 0; }
if source longer number of characters copy, strncpy
function not add string terminator, buffer2
might not contain string terminator , when treat terminated string have undefined behavior.
the solution simple: add terminator manually.
like
strncpy(buffer2,buffer,sizeof buffer2 - 1); buffer2[sizeof buffer2 - 1] = '\0';
Comments
Post a Comment