繁体   English   中英

C 逐行读取文件

[英]C read file line by line

我写了这个 function 从文件中读取一行:

const char *readLine(FILE *file) {

    if (file == NULL) {
        printf("Error: file pointer is null.");
        exit(1);
    }

    int maximumLineLength = 128;
    char *lineBuffer = (char *)malloc(sizeof(char) * maximumLineLength);

    if (lineBuffer == NULL) {
        printf("Error allocating memory for line buffer.");
        exit(1);
    }

    char ch = getc(file);
    int count = 0;

    while ((ch != '\n') && (ch != EOF)) {
        if (count == maximumLineLength) {
            maximumLineLength += 128;
            lineBuffer = realloc(lineBuffer, maximumLineLength);
            if (lineBuffer == NULL) {
                printf("Error reallocating space for line buffer.");
                exit(1);
            }
        }
        lineBuffer[count] = ch;
        count++;

        ch = getc(file);
    }

    lineBuffer[count] = '\0';
    char line[count + 1];
    strncpy(line, lineBuffer, (count + 1));
    free(lineBuffer);
    const char *constLine = line;
    return constLine;
}

function 正确读取文件,使用 printf 我看到 constLine 字符串也被正确读取。

但是,如果我使用 function 例如这样:

while (!feof(myFile)) {
    const char *line = readLine(myFile);
    printf("%s\n", line);
}

printf 输出乱码。 为什么?

如果您的任务不是发明逐行读取函数,而只是逐行读取文件,您可以使用包含getline()函数的典型代码片段(请参阅此处的手册页):

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;

    fp = fopen("/etc/motd", "r");
    if (fp == NULL)
        exit(EXIT_FAILURE);

    while ((read = getline(&line, &len, fp)) != -1) {
        printf("Retrieved line of length %zu:\n", read);
        printf("%s", line);
    }

    fclose(fp);
    if (line)
        free(line);
    exit(EXIT_SUCCESS);
}
FILE* filePointer;
int bufferLength = 255;
char buffer[bufferLength];

filePointer = fopen("file.txt", "r");

while(fgets(buffer, bufferLength, filePointer)) {
    printf("%s\n", buffer);
}

fclose(filePointer);

在你的readLine函数中,你返回一个指向line数组的指针(严格来说,一个指向它的第一个字符的指针,但这里的区别无关紧要)。 由于它是一个自动变量(即,它“在堆栈上”),当函数返回时内存会被回收。 你会看到胡言乱语,因为printf已经把它自己的东西放在了堆栈上。

您需要从函数返回一个动态分配的缓冲区。 你已经有了一个,它是lineBuffer 您所要做的就是将其截断为所需的长度。

    lineBuffer[count] = '\0';
    realloc(lineBuffer, count + 1);
    return lineBuffer;
}

添加(对评论中的后续问题的回应): readLine返回一个指向组成该行的字符的指针。 这个指针是你处理行内容所需要的。 当您使用完这些字符占用的内存时,这也是您必须传递给free 下面是如何使用readLine函数:

char *line = readLine(file);
printf("LOG: read a line: %s\n", line);
if (strchr(line, 'a')) { puts("The line contains an a"); }
/* etc. */
free(line);
/* After this point, the memory allocated for the line has been reclaimed.
   You can't use the value of `line` again (though you can assign a new value
   to the `line` variable if you want). */
//open and get the file handle
FILE* fh;
fopen_s(&fh, filename, "r");

//check if file exists
if (fh == NULL){
    printf("file does not exists %s", filename);
    return 0;
}


//read line by line
const size_t line_size = 300;
char* line = malloc(line_size);
while (fgets(line, line_size, fh) != NULL)  {
    printf(line);
}
free(line);    // dont forget to free heap memory

readLine()返回指向局部变量的指针,这会导致未定义的行为。

要四处走动,您可以:

  1. 在调用函数中创建变量并将其地址传递给readLine()
  2. 使用malloc()line分配内存 - 在这种情况下, line是持久的
  3. 使用全局变量,尽管这通常是一种不好的做法

使用fgets()从文件句柄中读取一行。

一个完整的fgets()解决方案:

#include <stdio.h>
#include <string.h>

#define MAX_LEN 256

int main(void)
{
    FILE* fp;
    fp = fopen("file.txt", "r");
    if (fp == NULL) {
      perror("Failed: ");
      return 1;
    }

    char buffer[MAX_LEN];
    // -1 to allow room for NULL terminator for really long string
    while (fgets(buffer, MAX_LEN - 1, fp))
    {
        // Remove trailing newline
        buffer[strcspn(buffer, "\n")] = 0;
        printf("%s\n", buffer);
    }

    fclose(fp);
    return 0;
}

输出:

First line of file
Second line of file
Third (and also last) line of file

请记住,如果您想从标准输入(而不是本例中的文件)读取,那么您要做的就是将stdin作为fgets()方法的第三个参数传递,如下所示:

while(fgets(buffer, MAX_LEN - 1, stdin))

附录

从 fgets() 输入中删除尾随换行符

c - 如何检测文件是否在c中打开

这个例子有一些错误:

  • 您忘记将 \\n 添加到您的 printfs 中。 错误消息也应该转到 stderr,即fprintf(stderr, ....
  • (不是很大,但是)考虑使用fgetc()而不是getc() getc()是一个宏, fgetc()是一个适当的函数
  • getc()返回一个int所以ch应该被声明为一个int 这很重要,因为将正确处理与EOF的比较。 某些 8 位字符集使用0xFF作为有效字符(例如 ISO-LATIN-1),并且EOF为 -1,如果分配给char则为0xFF
  • 该行存在潜在的缓冲区溢出

    lineBuffer[count] = '\\0';

    如果该行的长度正好是 128 个字符,则count在执行时为 128。

  • 正如其他人所指出的, line是一个本地声明的数组。 你不能返回指向它的指针。

  • strncpy(count + 1)最多将复制count + 1字符,但如果它命中'\\0'将终止因为您将lineBuffer[count]设置为'\\0'你知道它永远不会到达count + 1 但是,如果这样做了,它不会将终止的'\\0'放在上面,因此您需要这样做。 您经常会看到类似以下内容:

     char buffer [BUFFER_SIZE]; strncpy(buffer, sourceString, BUFFER_SIZE - 1); buffer[BUFFER_SIZE - 1] = '\\0';
  • 如果您malloc()返回一行(代替您的本地char数组),您的返回类型应该是char* - 删除const

void readLine(FILE* file, char* line, int limit)
{
    int i;
    int read;

    read = fread(line, sizeof(char), limit, file);
    line[read] = '\0';

    for(i = 0; i <= read;i++)
    {
        if('\0' == line[i] || '\n' == line[i] || '\r' == line[i])
        {
            line[i] = '\0';
            break;
        }
    }

    if(i != read)
    {
        fseek(file, i - read + 1, SEEK_CUR);
    }
}

这个如何?

const char *readLine(FILE *file, char* line) {

    if (file == NULL) {
        printf("Error: file pointer is null.");
        exit(1);
    }

    int maximumLineLength = 128;
    char *lineBuffer = (char *)malloc(sizeof(char) * maximumLineLength);

    if (lineBuffer == NULL) {
        printf("Error allocating memory for line buffer.");
        exit(1);
    }

    char ch = getc(file);
    int count = 0;

    while ((ch != '\n') && (ch != EOF)) {
        if (count == maximumLineLength) {
            maximumLineLength += 128;
            lineBuffer = realloc(lineBuffer, maximumLineLength);
            if (lineBuffer == NULL) {
                printf("Error reallocating space for line buffer.");
                exit(1);
            }
        }
        lineBuffer[count] = ch;
        count++;

        ch = getc(file);
    }

    lineBuffer[count] = '\0';
    char line[count + 1];
    strncpy(line, lineBuffer, (count + 1));
    free(lineBuffer);
    return line;

}


char linebuffer[256];
while (!feof(myFile)) {
    const char *line = readLine(myFile, linebuffer);
    printf("%s\n", line);
}

请注意,'line' 变量是在调用函数中声明然后传递的,因此您的readLine函数会填充预定义的缓冲区并返回它。 这是大多数 C 库的工作方式。

还有其他方法,我知道:

  • char line[]定义为静态( static char line[MAX_LINE_LENGTH] -> 它将在从函数返回后保持它的值)。 -> 不好,该函数不可重入,并且可能发生竞争条件 -> 如果你从两个线程调用它两次,它会覆盖它的结果
  • malloc()调用 char line[],并在调用函数时释放它 -> 太多昂贵的malloc s,并且将释放缓冲区的责任委托给另一个函数(最优雅的解决方案是在任何缓冲区上调用mallocfree在相同的功能)

顺便说一句,从char*const char* “显式”转换是多余的。

btw2,不需要malloc() lineBuffer,只需定义它char lineBuffer[128] ,所以你不需要释放它

btw3 不使用“动态大小堆栈数组”(将数组定义为char arrayName[some_nonconstant_variable] ),如果您不完全知道自己在做什么,则它仅适用于 C99。

实现方法从文件中读取和获取内容(input1.txt)

#include <stdio.h>
#include <stdlib.h>

void testGetFile() {
    // open file
    FILE *fp = fopen("input1.txt", "r");
    size_t len = 255;
    // need malloc memory for line, if not, segmentation fault error will occurred.
    char *line = malloc(sizeof(char) * len);
    // check if file exist (and you can open it) or not
    if (fp == NULL) {
        printf("can open file input1.txt!");
        return;
    }
    while(fgets(line, len, fp) != NULL) {
        printf("%s\n", line);
    }
    free(line);
}

希望这有帮助。 快乐编码!

这是我的几个小时......逐行读取整个文件。

char * readline(FILE *fp, char *buffer)
{
    int ch;
    int i = 0;
    size_t buff_len = 0;

    buffer = malloc(buff_len + 1);
    if (!buffer) return NULL;  // Out of memory

    while ((ch = fgetc(fp)) != '\n' && ch != EOF)
    {
        buff_len++;
        void *tmp = realloc(buffer, buff_len + 1);
        if (tmp == NULL)
        {
            free(buffer);
            return NULL; // Out of memory
        }
        buffer = tmp;

        buffer[i] = (char) ch;
        i++;
    }
    buffer[i] = '\0';

    // Detect end
    if (ch == EOF && (i == 0 || ferror(fp)))
    {
        free(buffer);
        return NULL;
    }
    return buffer;
}

void lineByline(FILE * file){
char *s;
while ((s = readline(file, 0)) != NULL)
{
    puts(s);
    free(s);
    printf("\n");
}
}

int main()
{
    char *fileName = "input-1.txt";
    FILE* file = fopen(fileName, "r");
    lineByline(file);
    return 0;
}

您应该使用 ANSI 函数来读取一行,例如。 获取。 调用后,您需要在调用上下文中使用 free(),例如:

...
const char *entirecontent=readLine(myFile);
puts(entirecontent);
free(entirecontent);
...

const char *readLine(FILE *file)
{
  char *lineBuffer=calloc(1,1), line[128];

  if ( !file || !lineBuffer )
  {
    fprintf(stderr,"an ErrorNo 1: ...");
    exit(1);
  }

  for(; fgets(line,sizeof line,file) ; strcat(lineBuffer,line) )
  {
    if( strchr(line,'\n') ) *strchr(line,'\n')=0;
    lineBuffer=realloc(lineBuffer,strlen(lineBuffer)+strlen(line)+1);
    if( !lineBuffer )
    {
      fprintf(stderr,"an ErrorNo 2: ...");
      exit(2);
    }
  }
  return lineBuffer;
}

我的工具从头开始:

FILE *pFile = fopen(your_file_path, "r");
int nbytes = 1024;
char *line = (char *) malloc(nbytes);
char *buf = (char *) malloc(nbytes);

size_t bytes_read;
int linesize = 0;
while (fgets(buf, nbytes, pFile) != NULL) {
    bytes_read = strlen(buf);
    // if line length larger than size of line buffer
    if (linesize + bytes_read > nbytes) {
        char *tmp = line;
        nbytes += nbytes / 2;
        line = (char *) malloc(nbytes);
        memcpy(line, tmp, linesize);
        free(tmp);
    }
    memcpy(line + linesize, buf, bytes_read);
    linesize += bytes_read;

    if (feof(pFile) || buf[bytes_read-1] == '\n') {
        handle_line(line);
        linesize = 0;
        memset(line, '\0', nbytes);
    }
}

free(buf);
free(line);

提供可移植的通用getdelim函数,测试通过 msvc、clang、gcc。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

ssize_t
portabl_getdelim(char ** restrict linep,
                 size_t * restrict linecapp,
                 int delimiter,
                 FILE * restrict stream) {
    if (0 == *linep) {
        *linecapp = 8;
        *linep = malloc(*linecapp);
        if (0 == *linep) {
            return EOF;
        }
    }

    ssize_t linelen = 0;
    int c = 0;
    char *p = *linep;

    while (EOF != (c = fgetc(stream))) {
        if (linelen == (ssize_t) *linecapp - 1) {
            *linecapp <<= 1;
            char *p1 = realloc(*linep, *linecapp);
            if (0 == *p1) {
                return EOF;
            }
            p = p1 + linelen;
        }
        *p++ = c;
        linelen++;

        if (delimiter == c) {
            *p = 0;
            return linelen;
        }
    }
    return EOF == c ? EOF : linelen;
}


int
main(int argc, char **argv) {
    const char *filename = "/a/b/c.c";
    FILE *file = fopen(filename, "r");
    if (!file) {
        perror(filename);
        return 1;
    }

    char *line = 0;
    size_t linecap = 0;
    ssize_t linelen;

    while (0 < (linelen = portabl_getdelim(&line, &linecap, '\n', file))) {
        fwrite(line, linelen, 1, stdout);
    }
    if (line) {
        free(line);
    }
    fclose(file);   

    return 0;
}

您犯了返回指向自动变量的指针的错误。 变量 line 在堆栈中分配,并且只在函数存在时才存在。 不允许返回指向它的指针,因为一旦它返回,内存就会分配给其他地方。

const char* func x(){
    char line[100];
    return (const char*) line; //illegal
}

为了避免这种情况,您要么返回一个指向驻留在堆上的内存的指针,例如。 lineBuffer 并且在完成之后调用 free() 应该是用户的责任。 或者,您可以要求用户将要写入行内容的内存地址作为参数传递给您。

我想要一个来自地面 0 的代码,所以我这样做是为了逐行阅读字典单词的内容。

字符 temp_str[20]; //您可以根据您的要求更改缓冲区大小以及文件中单行的长度。

注意我每次读取行时都用空字符初始化缓冲区。这个函数可以是自动的但是因为我需要一个概念证明并且想要一个字节一个字节地设计一个程序

#include<stdio.h>

int main()
{
int i;
char temp_ch;
FILE *fp=fopen("data.txt","r");
while(temp_ch!=EOF)
{
 i=0;
  char temp_str[20]={'\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0'};
while(temp_ch!='\n')
{
  temp_ch=fgetc(fp);
  temp_str[i]=temp_ch;
  i++;
}
if(temp_ch=='\n')
{
temp_ch=fgetc(fp);
temp_str[i]=temp_ch;
}
printf("%s",temp_str);
}
return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM