I see, i dinīt know how to pass the strings, and no one teach me about size_t.
I know i can use int bufsize, but i think the correct way is to use size_t (for sure a positive value).
Why size_t matters | Embedded . - A little to advanced for me.
size_t - C++ Reference
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
int count_lines(FILE * pFile, char *buffer, size_t bufsize, int nrlines_of_the_file);
int ask_user_input(int nrline_to_printf, int nrlines_of_the_file);
int printf_the_line(FILE * pFile, char *buffer, size_t bufsize, int nrline_to_printf);
int main(int argc, char** argv) {
char buffer[SIZE];
FILE * pFile;
if ((pFile = fopen("code.txt", "rt")) == NULL)
return -1;
int nrlines_of_the_file = 0;
int nrline_to_printf = 0;
// The file have at least one line
nrlines_of_the_file = count_lines(pFile, buffer, sizeof (buffer), nrlines_of_the_file);
nrline_to_printf = ask_user_input(nrline_to_printf, nrlines_of_the_file);
printf_the_line(pFile, buffer, sizeof (buffer), nrline_to_printf);
return (EXIT_SUCCESS);
}
int count_lines(FILE * pFile, char *buffer, size_t bufsize, int nrlines_of_the_file) {
while (fgets(buffer, bufsize, pFile) != NULL) {
if (buffer[strlen(buffer) - 1] == '\n') {
nrlines_of_the_file++;
} else if (feof(pFile)) { // only happens at end of file when last line doesn't have \n - user forgets to press "Enter"
nrlines_of_the_file++;
}
}
rewind(pFile);
return nrlines_of_the_file;
}
int ask_user_input(int nrline_to_printf, int nrlines_of_the_file) {
do {
printf("What line you want to print ?\n(put a number between 1 and %d)\n", nrlines_of_the_file);
scanf("%d", &nrline_to_printf);
} while (nrline_to_printf < 1 || nrline_to_printf > nrlines_of_the_file);
return nrline_to_printf;
}
int printf_the_line(FILE * pFile, char *buffer, size_t bufsize, int nrline_to_printf) {
int nrline_on_the_file = 0;
while (fgets(buffer, bufsize, pFile) != NULL) {
if (nrline_to_printf == nrline_on_the_file + 1) {
fputs(buffer, stdout);
return (EXIT_SUCCESS);
}
nrline_on_the_file++;
}
return 0;
}