c - 用 C 中的 fgets 覆盖我的数组

标签 c arrays file csv fgets

C 语言的一切都在这里...

我想读取一个 csv 文件,其中每一行都有单独的 fgets。我通过浏览我的 csv 文件、读取特定行、将其保存到我的数组中并增加我的连续变量来完成此操作。

我想编写一个程序将 csv 文件转换为具有特定行的特定 header 的 JSON,但这还有很长的路要走...

这是我的代码:

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

int main() {
    printf("\n\n\nCode starts...\n");

   int i = 0;
   int j = 0;

   char content[1000];
   char * contentArray[2][9];

   FILE * regel1 = fopen("Regel-1.csv","r");

   while(!feof(regel1)){
        fgets(content, sizeof(content), regel1);
        contentArray[i][j] = content;
        printf("\nThis is contentArray[%i][0]: %s\n", i, contentArray[i][0]);
        i++;
   }

   printf("\nWhile-Loop finished...\n");

   for(int n = 0; n<=1; n++){
       printf("\nThat is contentArray[%i][0]: %s\n", n, contentArray[n][0]);
   }

   fclose(regel1);
     return 0;
}

正如您在我的输出中看到的,它首先将 csv 文件的两行不同的行保存到数组中,但然后...据我从测试中得知...用 fgets 覆盖第一个数组条目...

Code starts...

This is contentArray[0][0]: ME;Wie ist der übliche Abstand der gegnerischen Spieler bei einer mit dem Fuß ausgeführten Spielfortsetzung, z.B. dem Anstoß?;9 Meter;9,15 Meter;10 Meter;2;2;;;

This is contentArray[1][0]: ME;Welche Art von Freistoß wird an einem beliebigen Punkt innerhalb des Torraums ausgeführt?;Direkte und Indirekte Freistöße für die verteidigende Mannschaft.;Direkte Freistöße für die angreifende Mannschaft.;Indirekte Freistöße für die angreifende Mannschaft.;1;2;;;

While-Loop finished...

That is contentArray[0][0]: ME;Welche Art von Freistoß wird an einem beliebigen Punkt innerhalb des Torraums ausgeführt?;Direkte und Indirekte Freistöße für die verteidigende Mannschaft.;Direkte Freistöße für die angreifende Mannschaft.;Indirekte Freistöße für die angreifende Mannschaft.;1;2;;;

That is contentArray[1][0]: ME;Welche Art von Freistoß wird an einem beliebigen Punkt innerhalb des Torraums ausgeführt?;Direkte und Indirekte Freistöße für die verteidigende Mannschaft.;Direkte Freistöße für die angreifende Mannschaft.;Indirekte Freistöße für die angreifende Mannschaft.;1;2;;;

我非常感谢您的帮助。

提前致谢

GMOSS

最佳答案

实际上你有两个问题。

第一个问题在 Why is “while ( !feof (file) )” always wrong? 中被询问和回答。 .

第二个,这是你问的问题,是你有一个指针矩阵。并且您初始化的所有指针都将全部指向同一位置:数组content中的第一个字符。

要解决您的问题,可以将 contentArray 设为数组的数组of arrays,然后从 contents 复制字符串。或者使用常用的 strdup 函数来复制字符串。

如果您使用 strdup,那么请不要忘记使用 free 来释放 strdup 分配的内存。

<小时/>

还有其他一些事情您还可以改进,但不会影响您当前的问题。例如错误处理。如果打开文件失败且 fopen 返回空指针,会发生什么情况?您需要处理这个问题,而不是继续,因为这会导致 undefined behavior .

关于c - 用 C 中的 fgets 覆盖我的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50772804/

相关文章:

c - 如何在c中以像素级减小或增大图像的大小

javascript - 获取数组对象中第一个对象的键

python - 查看 .npy 图像

java - 如何在 Java 中保留插入顺序、恒定时间检索和动态调整大小

file - 文件格式是如何创建的?如果都是二进制的,编码如何改变文件类型?

java - 在 Eclipse JAR 导出中包含文本文件?

c - 如何在 C 中跳过输入文件的第一行?

c - 仅当使用 -std=c99 时,我才会收到隐式声明错误

计算OpenSSL加密和解密的缓冲区大小?

c++ - typeid(equalizing) 中类型定义及其含义的区别