I got this piece of code:
void scanLinesforArray(FILE* file, char search[], int* lineNr){
char line[1024];
int line_count = 0;
while(fgets(line, sizeof(line),file) !=NULL){
++line_count;
printf("%d",line_count);
printf(line);
char *temp = malloc(strlen(line));
// strncpy(temp,line,sizeof(line));
// printf("%s\n",temp);
free(temp);
continue;
}
}
This will print all lines of the file, but as soon as I uncomment the strncpy(), the program just stops without error.
Same happens as soon as I use strstr() to compare the line to my search variable.
I tried the continue statement and other redundant things, but nothing helps.
Many problems:
Do not print a general string as a format
Code risks undefined behavior should the string contain a
%.Bad size
strncpy(temp,line,sizeof(line));is likestrncpy(temp,line, 1024);, yettemppoints to less than 1024 allocated bytes. Code attempts to write outside allocated memory. Undefined behavior (UB).Rarely should code use
strncpy().Bad specifier
%sexpects a match string.tempdoes not point to a string as it lacks a null character. Instead allocated for the'\0'.No compare
"Can't compare Lines of a file in C" is curious as there is no compare code.
Recall
fgets()typically retains a'\n'inline[].Perhaps
Advanced: Sample better performance code.