Reputation: 49
I want to read content from file's end and print it to the screen. But fseek() function doesn't give permission me to reach line which is I need. I expressed in comment lines what I want to do. How can I solve this problem? Thanks in advance
#include <stdio.h>
int main()
{
FILE *ptrFILE;
int i, k, value; // Variables for loops and values inside of file
if ((ptrFILE = fopen("Test.txt", "w"))==NULL) // Open a file to just write knowledge in it
{
printf("File couldn't open..\n\n");
}
for (i = 1; i <= 20; i++) // Write 20 lines to file (Multiplying numbers with 5 from 1 to 20)
{
fprintf(ptrFILE, "%d\n", i * 5);
}
fclose(ptrFILE); // Close the file
ptrFILE = fopen("Test.txt", "r"); // Open file read mode
printf("To display content from the beginning enter positive number or vice versa : "); // Read user choice
scanf("%d", &i);
if (i > 0)
{
fseek(ptrFILE, 0L, SEEK_SET);
for (k = 1; k <= i; k++)
{
fscanf(ptrFILE, "%d\n", &value);
printf("%d\n", value);
}
}
else
{
fseek(ptrFILE, -10L, SEEK_END); // Why does C give permission to write instead of -10L like I expressed below?
fscanf(ptrFILE, "%d\n", &value);
printf("%d\n", value);
}
/* Like this!!
else
{
int x; <<<<<<<<<<<<<<<<<<<<<<<<<<<
x= i*5; <<<<<<<<<<<<<<<<<<<<<<<<<<<
fseek(ptrFILE, -xL, SEEK_END); <<<<<<<<<<<
fscanf(ptrFILE, "%d\n", &value);
printf("%d\n", value);
}*/
fclose(ptrFILE);
return 0;
}
Upvotes: 2
Views: 285
Reputation: 2566
To convert your value x
to a negative long value, you must use
fseek(ptrFILE, -((long) x), SEEK_END);
The issue with this code is, that you can not be sure that there actually is a number at the position you are seeking to. There could as well be a newline \n
character, depending on what you wrote there before.
Upvotes: 1