School-Coding-Cpp/sfusi/readRandomLine_textfile.c

38 lines
675 B
C

#include <stdio.h>
#include <string.h>
#define SIZE_LINE 1000+1
void readRandomLine(FILE * file, int myRow);
int main(void) {
FILE * file = fopen("parole.txt", "rt");
if (file != NULL) {
int myRow = 2;
readRandomLine(file, myRow);
fclose(file);
} else {
perror("Error (source)");
}
return 0;
}
void readRandomLine(FILE * file, int myRow) {
char str[SIZE_LINE];
int newRow = 1;
while (fgets(str, sizeof(str), file) != NULL) {
if (newRow == myRow) {
printf("Current line (line no. %d): %s\n", myRow, str);
return;
}
newRow++;
}
printf("Line no. %d does not exist in the file.\n", myRow);
}