#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
FILE* fptr = fopen(argv[1],"r");
if(fptr == NULL)
{
perror("error:");
exit(1);
}
int count = 0;
//getline主要是使用malloc生成n字节空间,用lineptr指向,如果发现空间不够,使用realloc重新分配
char* lineptr = NULL;//指向新分配的空间
size_t n = 0;//分配空间的地址大小
while(1)
{
if(getline(&lineptr,&n,fptr) == -1) break;
fprintf(stdout,"%6d %s",count++,lineptr);
}
free(lineptr);
fclose(fptr);
exit(0);
}
官方示例:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
FILE *stream;
char *line = NULL;
size_t len = 0;
ssize_t nread;
if (argc != 2) {
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
exit(EXIT_FAILURE);
}
stream = fopen(argv[1], "r");
if (stream == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
while ((nread = getline(&line, &len, stream)) != -1) {
printf("Retrieved line of length %zd:\n", nread);
fwrite(line, nread, 1, stdout);
}
free(line);
fclose(stream);
exit(EXIT_SUCCESS);
}