從檔案中讀取行
stdio.h
標頭定義了 fgets()
功能。此函式從流中讀取一行並將其儲存在指定的字串中。當讀取 n - 1
字元,讀取換行符('\n'
)或到達檔案結尾(EOF)時,該函式停止從流中讀取文字。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 80
int main(int argc, char **argv)
{
char *path;
char line[MAX_LINE_LENGTH] = {0};
unsigned int line_count = 0;
if (argc < 1)
return EXIT_FAILURE;
path = argv[1];
/* Open file */
FILE *file = fopen(path, "r");
if (!file)
{
perror(path);
return EXIT_FAILURE;
}
/* Get each line until there are none left */
while (fgets(line, MAX_LINE_LENGTH, file))
{
/* Print each line */
printf("line[%06d]: %s", ++line_count, line);
/* Add a trailing newline to lines that don't already have one */
if (line[strlen(line) - 1] != '\n')
printf("\n");
}
/* Close file */
if (fclose(file))
{
return EXIT_FAILURE;
perror(path);
}
}
使用引數呼叫程式,該引數是包含以下文字的檔案的路徑:
This is a file
which has
multiple lines
with various indentation,
blank lines
a really long line to show that the line will be counted as two lines if the length of a line is too long to fit in the buffer it has been given,
and punctuation at the end of the lines.
將導致以下輸出:
line[000001]: This is a file
line[000002]: which has
line[000003]: multiple lines
line[000004]: with various indentation,
line[000005]: blank lines
line[000006]:
line[000007]:
line[000008]:
line[000009]: a really long line to show that the line will be counted as two lines if the le
line[000010]: ngth of a line is too long to fit in the buffer it has been given,
line[000011]: and punctuation at the end of the lines.
line[000012]:
這個非常簡單的例子允許固定的最大線長度,這樣較長的線將有效地計為兩條線。fgets()
函式要求呼叫程式碼提供用作讀取行的目標的記憶體。
POSIX 使 getline()
功能可用,而是在內部分配記憶體以根據需要擴充套件任何長度的行(只要有足夠的記憶體)。