我想从文件结尾阅读内容并将其打印到屏幕上。但是fseek()函数并没有允许我到达我需要的行。我在评论中表达了我想做的事情。我怎么解决这个问题?提前致谢
#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;
}
答案 0 :(得分:1)
要将您的值x
转换为负长值,您必须使用
fseek(ptrFILE, -((long) x), SEEK_END);
此代码的问题是,您无法确定 是否在您正在寻找的位置。可能还有换行符\n
,取决于你之前写的内容。