0
我試圖編寫一個程序來讀取文件,並輸出文件的行。它將從最後一行開始,然後打印第二行到最後一行,然後是最後一行,第二行到最後一行,然後是第三行到最後一行,依此類推。 ((c = fgetc(myFile)!= EOF))while((c = fgetc(myFile))!= EOF) 這是循環的條件, 代碼(c = fgetc ....)關閉。
有人可以幫我解決這個問題嗎?
謝謝。學習如何讀取和輸出文件中的行C
void tail(FILE* myFile, int num) //Tail function that prints the lines
according to the user specified number of lines
{
int start, line = 0, counter = 0;
char c, array[100];
while((c = fgetc(myFile) != EOF))
{
if(c=='\n')
line++;
}
start = line - num; //Start location
fseek(myFile, 0, SEEK_SET); //Goes to the start of the file
while(fgets(array, 100, myFile) != NULL)
{
if(counter >start)
{
printf("%s",array); //Prints the string
}
counter++;
}
fclose(myFile); //Closes the file
}