C读取文件的整行 [英] C read entire line of file

查看:103
本文介绍了C读取文件的整行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 C 中编程工具.该程序的一部分是使用文本文件并逐行读取它,同时将所有行存储到数组中以供将来使用.

I am trying to program a tool in C. Part of this program is to use a text file and read it line by line, while storing all lines into an array to have it available for future use.

这就是我到目前为止所拥有的:

That's what I have so far:

int main(){
    FILE *fp = fopen("file.txt", "ab+");
    if (fp == NULL) {
        printf("FILE ERROR");
        return 1;
    }

    int lines = 0;
    int ch = 0;

    while(!feof(fp)){
        ch = fgetc(fp);
        if(ch == '\n'){
        lines++;
        }
    }

    printf("%d\n", lines);
    if (lines>0){
        int i = 0;
        int numProgs = 0;
        char* programs[lines];
        char line[lines];
        FILE *file;
        file = fopen("file.txt", "r");
        while(fgets(line, sizeof(line), file) != NULL){
        programs[i] = strdup(line);
        i++;
        numProgs++;
    }
    for (int j= 0; j<sizeof(programs); j++){
        printf("%s\n", programs[j]);
    } 
    fclose(file);
    fclose(fp);
    return 0;
}

我的问题是我正在获得以下输出:

My problem is im getting this output:

6(文件中的行数) Segmentation fault

6 (the number of lines in the file) Segmentation fault

如何在不知道一行开始多长时间的情况下,逐行阅读完整的内容.在PHP中,我可以很轻松地做到这一点,但是如何在 C 中做到这一点?

How can I read a complete line by line , without knowing how long the line is in the beginning. in PHP I can do that very easily, but how can I do that in C?

谢谢您的提示!

推荐答案

在线尝试

Try Online

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

char * readLine (FILE * file)
{
    size_t len = 0;
    int c = 0, i = 0;
    long pos = ftell(file);
    char * out = 0;

    // read the whole line
    do { c = fgetc(file); len++; }
    while (c!='\0' && c!='\n' && c!=EOF);

    // if the cursor didn't move return NULL
    if (pos == ftell(file) && c == EOF) return 0;

    // allocate required memory
    out = (char*)malloc(len+1);

    // rewind cursor to beginning of line
    fseek (file, pos, SEEK_SET);

    // copy the line
    do { out[i++] = fgetc(file); }
    while (c!='\0' && c!='\n' && c!=EOF);

    // make sure there's \0 at the end
    out[i] = '\0';

    return out;
}


int main (void)
{
//  FILE * file = fopen("test.txt", "r");
    char * line = readLine(stdin);

    while(line)
    {
        printf(line); // print current line
        free(line); // free allocated memory
        line = readLine(stdin); // recur
    }

    return 0;
}

这篇关于C读取文件的整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆