#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/