C 读取整行文件

标签 c fopen fgets

<分区>

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

这就是我目前所拥有的:

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;
}

我的问题是我得到这个输出:

6(文件中的行数) 段错误

如何在不知道该行开头有多长的情况下逐行阅读完整内容。在 PHP 中我可以很容易地做到这一点,但我如何在 C 中做到这一点?

感谢任何提示!

最佳答案

像这样修复:

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

int main(void){
    FILE *fp = fopen("file.txt", "r");//!
    if (fp == NULL) {
        fprintf(stderr, "FILE ERROR\n");
        return 1;
    }

    int lines = 0;
    int ch = 0;
    int len = 0;//! length of line
    int max_len = 0;//! max length of line

    while((ch = fgetc(fp))!=EOF){//!
        ++len;
        if(ch == '\n'){
            if(max_len < len)
                max_len = len;
            ++lines;
            len = 0;
        }
    }
    if(len)
        ++lines;

    fprintf(stderr, "%d lines.\n", lines);

    if (lines > 0){
        int numProgs = 0;
        char *programs[lines];//use malloc, char **programs = malloc(lines * sizeof(*programs));
        char line[max_len+1];//!

        rewind(fp);//!
        while(fgets(line, sizeof(line), fp))
            programs[numProgs++] = strdup(line);//!

        for (int j= 0; j < numProgs; j++){//!
            printf("%s", programs[j]);//!
            free(programs[j]);//!
        } 
    }
    fclose(fp);

    return 0;
}

关于C 读取整行文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38775052/

相关文章:

C - 时间过去了

c - 逐行读取文本文件并从缓冲区扫描 - C

c - 如何使用 fgets() 从文件中提取一行文本?

c - 我恢复的 IMG 与恢复 CS50 中的原始 IMG 不匹配

C中全局变量的条件初始化

c - Phar Lap 汇编程序 : I Need information/documentation and binaries if possible

像 __TIME__ 这样的 C++ 预处理器指令有时不会改变/不会更新

c - 如何在 C 中打开文件以读取和写入其他文件?

codeigniter - 错误: HTTP/1.1 401 Unauthorized

C:使用 fread()/fgets() 而不是 fgetc() 逐行读取文本文件(具有可变长度行)( block I/O 与字符 I/O)