c - 如何指示文件的最后一行

标签 c arrays

我想逐行读取txt并将其存储到数组中; 我喜欢成功地在数组中逐行存储; 我分别使用 printf("%s", loadtext[i])i= 0,1,2,3-20 来检查数组中存储的内容; 但我意识到 for 循环已经执行了 1912 次 在 for 循环后面输入 printf("%d", i);

假设我的txt存储如下:

I am a jerk
I am a noob

I am an idiot
I am done

我有另一个程序可以在该程序运行时向文本文件添加新行。 如何检测 我完成 或稍后添加的新行是最后一行,以不允许 for 循环执行如此多次?

这是我的代码

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

int main(){
    FILE *fp = fopen("abc.txt","r");
    int i = 0,j=0,k=0;
    char ch[10000];
    char loadtext[100][100];
    for (i=0; ch[i] != EOF; i++){
        ch[i] = fgetc(fp);
        if (ch[i] != '\n'){
            loadtext[j][k] = ch[i];
            k++;
        }
        if(ch[i] == '\n'){
            loadtext[j][k] = ch[i];
            k=0;
            j++;
        }
    }
    printf("%s", loadtext[0]);
    printf("%s", loadtext[1]);
    printf("%s", loadtext[2]);
    fclose(fp);
    return 0;
}

最佳答案

要将整个文件读取到代表行的 char 指针“数组”中,您可以执行以下操作:

#include <stddef.h>  // size_t
#include <stdlib.h>  // EXIT_SUCCESS, EXIT_FAILURE
#include <stdio.h>   // malloc(), realloc(), free(), fgets()
#include <string.h>  // strlen(), strcpy()

enum { BUFFER_SIZE = 30 };  // whatever line length you suspect the input file to be + 1

int main(void)
{
    char const *filename = "test.txt";
    FILE *is = fopen(filename, "r");
    if (!is) {
        fprintf(stderr, "Couldn't open \"%s\" for reading :(\n\n", filename);
        return EXIT_FAILURE;
    }

    int result = EXIT_SUCCESS;  // assume a happy ending
    char buffer[BUFFER_SIZE];
    size_t num_lines = 0;
    char **lines = NULL;

    while (fgets(buffer, sizeof(buffer), is)) {
        ++num_lines;
        char **temp = realloc(lines, num_lines * sizeof(*lines));
        if (!temp) {
            fputs("Not enough memory :(\n\n", stderr);
            fclose(is);
            result = EXIT_FAILURE;
            goto cleanup;
        }
        lines = temp;

        size_t length = strlen(buffer);
        length = strlen(buffer);

        // remove a trailing newline if any:
        if (length && buffer[length - 1] == '\n')
            buffer[--length] = '\0';

        size_t line_length = length;
        lines[num_lines - 1] = malloc((length + 1) * sizeof(*lines));
        if (!lines[num_lines - 1]) {
            fputs("Not enough memory :(\n\n", stderr);
            fclose(is);
            result = EXIT_FAILURE;
            goto cleanup;
        }

        strcpy(lines[num_lines - 1], buffer);

        // as long as the buffer has been filled completely by the previous
        // call to fgets() and a next call to fgets() also succeeds:
        while (length == BUFFER_SIZE - 1 && fgets(buffer, sizeof(buffer), is)) {
            length = strlen(buffer);

            // remove a trailing newline if any:
            if (length && buffer[length - 1] == '\n')
                buffer[--length] = '\0';

            char *temp = realloc(lines[num_lines - 1], line_length + length + 1);
            if (!temp) {
                fputs("Not enough memory :(\n\n", stderr);
                fclose(is);
                result = EXIT_FAILURE;
                goto cleanup;
            }
            lines[num_lines - 1] = temp;
            strcpy(lines[num_lines - 1] + line_length, buffer);
            line_length += length;
        }
    }
    fclose(is);

    // use lines:
    for (size_t i = 0; i < num_lines; ++i)
        puts(lines[i]);

cleanup:
    for (size_t i = 0; i < num_lines; ++i)
        free(lines[i]);
    free(lines);
    return result;
}

仅使用固定大小的二维数组和 fgetc()*):

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

enum { MAX_LINES = 100, MAX_LINE_LENGTH = 100 };

int main(void)
{
    char const *filename = "test.txt";
    FILE *is = fopen(filename, "r");
    if (!is) {
        fprintf(stderr, "Couldn't open \"%s\" for reading :(\n\n", filename);
        return EXIT_FAILURE;
    }

    char text[MAX_LINES][MAX_LINE_LENGTH + 1] = { 0 };  // zero-initialize the array
                                                        // so we don't have to care
    size_t num_lines = 0;                               // about zero terminating
    size_t current_column = 0;                          // every line

    int ch;
           // as long as we are still inside the bounds of the fixed size array
           // and fgetc() doesn't return EOF
    while (num_lines < MAX_LINES && current_column < MAX_LINE_LENGTH &&
           (ch = fgetc(is)) != EOF)
    {
        if (ch == '\n') {    // "move" num_lines and current_column to the next
            ++num_lines;     // line.
            current_column = 0;
            continue;
        }

        text[num_lines][current_column++] = ch;
    }

    if (ch != EOF) {
        fputs("The file is too big :(\n\n", stderr);
        return EXIT_FAILURE;
    }

    for (size_t i = 0; i <= num_lines; ++i)
        puts(text[i]);
}

*) 也可以使用 fgets() 来完成。

关于c - 如何指示文件的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53564875/

相关文章:

连接错误 : "No route to host"

java - 使用 hashCode 获取数组 java 元素的索引

arrays - 具有 'import Foundation' 的 Swift 不同数组行为

arrays - bash 中是否有一个 array_combine 函数,我可以在其中从两个函数创建一个关联数组?

c - 在C中传递指向静态全局变量的指针

c - C 中的客户端服务器应用程序中缺少字节

ios - 取消选择 TableView 时从数组中删除对象

Java:匹配两个不同类型的数组

c++ - 如何捕获 C 和 C++ 中的运行时错误?

C:共享内存和 fork ,打印语句执行多次