School-Coding-Cpp/sfusi/readRandomLine_textfile.cpp

40 lines
723 B
C++

#include <iostream>
#include <cstring>
#define SIZE_LINE 1000+1
using namespace std;
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) {
cout << "Current line (line no. " << myRow << "): " << str << endl;
return;
}
newRow++;
}
cout << "Line no. " << myRow << " does not exist in the file." << endl;
}