I want to create a function which has a text file as input with a line number and returns the string which represents the line in the number given as argument, in C langage. I've written this function (getLineFromFile) but I think it changes the content of my file, because I tried to use it in one other function but it seems to act weird(in the function (compiled)). these are the codes of my fuction getLineFromFile and the function "compiled", in compiled, when I run it gives me weird caracteres which doesnt represent my line. Can you help me I dont see where is the problem with the function getLineFromFile, I think the function getNumberOfLines has also problems, I want her to return 0 when the file is empty. thank you
#include <stdlib.h>
#include <string.h>
char* getLineFromFile(FILE *fp, int lineNumber)// si on depasse le nb de lignes, elle renvoie la derniere
{
char *str;
int i;
str = malloc(sizeof(char) * 80);// disons que ca ne depasse pas 80
for (i = 1 ; i <= lineNumber; i++)
fgets(str, 80, fp);
str[strlen(str) - 1] = '\0';
return str;
}
/// count the number of non empty lines in a file
int count_number_of_lines(FILE *fp) {
int count = 0;
char line[256];
while (fgets(line, sizeof(line), fp) != NULL) {
if (strlen(line) > 0) {
count++;
}
}
return count;
}
int compiled(FILE* fp){
char *line =malloc(sizeof(char)*80);
int nb_lines=count_number_of_lines(fp);
printf("number of lines : %d \n", nb_lines);
for (int j=1;j<=nb_lines;j++){
line=getLineFromFile(fp,j);
printf("%s \n",line);
}
return 0;
}
int main()
{
FILE *fichier=fopen("CodeSource.txt","r");
char *str=malloc(sizeof(char)*80);
int nb_lines=count_number_of_lines(fichier);
for (int j=1;j<=nb_lines;j++){
str=getLineFromFile(fichier,j);
printf("%s \n",str);
}
free(str);
return 0;
}