[英]C: Reading last n lines from file and printing them
我正在嘗試從文件中讀取最后 n 行,然后打印它們。 要閱讀我正在使用fgets()
的行,它似乎工作正常。 但是,當我嘗試打印存儲在數組中的最后 n 行時,它只打印最后一行 n 次。 我在數組中存儲字符串的方式似乎有問題。 這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int agrc, char** agrv) {
FILE* input;
input = fopen(agrv[1], "r");
int n = *agrv[2]-'0';
int line = 0;
char text[11];
char** tab = malloc(1000000*sizeof(text));
while(fgets(text, sizeof(text), input) != 0) {
tab[line] = text;
line++;
}
fclose(input);
int jump = line-n;
for(int i=jump; i<line; i++) {
printf("%s\n", tab[i]);
}
}
任何幫助,將不勝感激。 提前致謝!
編輯:
我已將我的 while 循環更改為此。 但是,它仍然不起作用。
while(fgets(text, sizeof(text), input) != 0) {
char text2[11];
strcpy(text2, text);
tab[line] = text2;
line++;
}
tab[line] = text;
將tab[line]
設置為指向text
的開頭。 所以你最終所有的tab[i]
都指向同一個地方,即text
的開頭。
您需要將從文件中讀取的每一行復制到 memory 中的不同位置。
如果您看到可以實現您希望實現的工作代碼,它可能會增加您的理解。 因為您的 OP 只能顯示 1-9“最后一行”,所以此代碼不會嘗試 go 超出“微薄”的數量。 此外,此代碼適用於行“中等長度”的文件。 應該清楚在哪里可以進行更改。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h> // for 'isdigit()'
// Factor processing into functions for clarity
void tail( FILE *ifp, size_t n ) {
char text[ 9 ][ 126 + 1 + 1 ]; // 9 'rows' up to 128 bytes each
size_t lnCnt = 0;
while( fgets( text[ lnCnt % 9 ], sizeof text[0], ifp ) != NULL )
lnCnt++;
// Do the math to workout what is wanted and what's available
if( lnCnt < n )
n = lnCnt, lnCnt = 0;
else
lnCnt += 9 - n;
// output
while( n-- )
printf( "%s", text[ lnCnt++ % 9 ] );
}
int main( int argc, char *argv[] ) {
// Check parameters meet requirements
if( argc != 3 || !isdigit( argv[ 2 ][ 0 ] ) ) {
fprintf( stderr, "Usage: %s filename #lines (1-9)\n", argv[ 0 ] );
exit( EXIT_FAILURE );
}
// Check functions didn't fail
FILE *ifp = fopen( argv[ 1 ], "r" );
if( ifp == NULL ) {
fprintf( stderr, "Cannot open '%s'\n", argv[ 1 ] );
exit( EXIT_FAILURE );
}
// do processing
tail( ifp, argv[ 2 ][ 0 ] - '0' );
// clean up
fclose( ifp );
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.