c - 从 C 中的文件读取时数组未正确递增

标签 c arrays file-io

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

#define ARRAY_MAX 100

int main() {

    FILE *input, *output;
    char *token[100];
    char buf[100];
    int count = 0;
    input = fopen("/Users/home/Desktop/test.txt", "r");
    output = fopen("/Users/home/Desktop/test2.txt", "w");

    while (fgets(buf, sizeof(buf), input) != NULL) {
        token[count] = strtok(buf, "\n");
        ++count;
    }

    for (int i = 0; i<count; i++) {
        printf("%s\n", token[i]);
    }

    printf("%d\n\n" ,count);
    return 0 ;

}

当我运行这段代码时,我得到如下输出

第 3 行

第 3 行

第 3 行

而不是得到像

这样的结果

第 1 行

第 2 行

第 3 行

我做错了什么?

最佳答案

strtok() 每次都在相同的 buf 上运行,因此每次都会返回相同的地址。当循环完成时,最后读取的值在缓冲区中,所以这就是打印的内容。

您想保存以下行的副本:

while (fgets(buf, sizeof(buf), input) != NULL) {
    token[count] = strdup( strtok(buf, "\n") );
    ++count;
}

关于c - 从 C 中的文件读取时数组未正确递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26679650/

相关文章:

arrays - 在scala中,如何找到数组元素的大小

php - 分类是如何工作的?

python - 批量重命名目录中的文件

在c中将整数转换为32位二进制

c++ - VC++ 9 QT 项目,转换为 Eclipse CDT

java - 调用方法的格式

java - try/catch block 中的代码未执行

ruby - 将大型数据库表导出到 csv 文件时流式传输到 ruby​​ 中的文件

C: conio 颜色转十六进制代码/RGB

c - C语言中的指针(代码解释)