【问题标题】:how to read a file and split each readed line into variables or array如何读取文件并将每个读取的行拆分为变量或数组
【发布时间】:2014-05-05 05:13:52
【问题描述】:

大家好,提前非常感谢,我想在这里完成的是正在使用 ansi C 读取文件,该文件包含文本,并且每一行都包含一个字符串,如下所示:

andreuga|460325945878913024|Y sorry por los que no querían pero ITESO ahí te voy|1398585232|0|0 

现在正在做的是读取该 file.txt 并将该字符串拆分为该输出:

res[0] = andreuga
res[1] = 460325945878913024
res[2] = Y sorry por los que no querÝan pero ITESO ahÝ te voy
res[3] = 1398585232
res[4] = 0
res[5] = 0
res[6] = (null)

所以我想要做的是读取文件并在读取每一行时拆分字符串并将该值保存到一个结构中,以便稍后我可以使用该结构并使用我拥有的另一个函数插入到数据库中。但我的主要问题是在从文件中读取每一行时拆分字符串。这是代码:

#include <string.h>

int main(){
    char    str[]= "andreuga|460325945878913024|Y sorry por los que no querían pero ITESO ahí te voy|1398585232|0|0";
    char ** res  = NULL;
    char *  p    = strtok (str, "|");
    int n_spaces = 0, i;


    /* split string and append tokens to 'res' */

    while (p) {
      res = realloc (res, sizeof (char*) * ++n_spaces);

      if (res == NULL)
        exit (-1); /* memory allocation failed */

      res[n_spaces-1] = p;

      p = strtok (NULL, "|");
    }

    /* realloc one extra element for the last NULL */

    res = realloc (res, sizeof (char*) * (n_spaces+1));
    res[n_spaces] = 0;

    /* print the result */

    for (i = 0; i < (n_spaces+1); ++i)
      printf ("res[%d] = %s\n", i, res[i]);

    /* free the memory allocated */

    free (res);

    return 0;
}
///////////////////////OUTPUT:
res[0] = andreuga
res[1] = 460325945878913024
res[2] = Y sorry por los que no querÝan pero ITESO ahÝ te voy
res[3] = 1398585232
res[4] = 0
res[5] = 0
res[6] = (null)

还要提一下,在这里我尝试加入两个代码失败。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include "libpq-fe.h"

#define LONG_MAX_LINEA  1024
#define NOM_ARCHIVO  "twitsDB.txt"


typedef struct tweet
{
 int  IDTweet;
 char IDCreator[20];
 char IDSentimentAnalysis[20];
 char HashTag[141];
 char Content[141];
 char CreationDate[30];    // time.h!!!
 char Retweet[20];
 char Favorites[20];
}Tweet;

int main(void)
{
   FILE *entrada;
   char linea[LONG_MAX_LINEA];

   char str[200];
   char ** res  = NULL;
   char *  p    = strtok (str, "|");
   int n_spaces = 0, i;
   int j = 0;

   printf("\n programa para leer una archivo");
   printf("\n-------------------------------");

   if ((entrada = fopen(NOM_ARCHIVO, "r")) == NULL){
      perror(NOM_ARCHIVO);
      return EXIT_FAILURE;
   }

   //Tweet tweet1;
   while (fgets(linea, LONG_MAX_LINEA, entrada) != NULL)
   {
      printf("%d %s", j,linea);


      //
        str[j] = linea;
        /* split string and append tokens to 'res' */

        while (p) {
          res = realloc (res, sizeof (char*) * ++n_spaces);

          if (res == NULL)
            exit (-1); /* memory allocation failed */

          res[n_spaces-1] = p;

          p = strtok (NULL, "|");
        }

        /* realloc one extra element for the last NULL */

        res = realloc (res, sizeof (char*) * (n_spaces+1));
        res[n_spaces] = 0;

        /* print the result */

        for (i = 0; i < (n_spaces+1); ++i)
          printf ("res[%d] = %s\n", i, res[i]);

        /* free the memory allocated */

        free (res);
      //

//      strcpy(tweet1.Content, "prueba tweet");
//      strcpy(tweet1.IDCreator, "1");
//      strcpy(tweet1.Favorites, "1");
//      strcpy(tweet1.Retweet, "1");
//      strcpy(tweet1.CreationDate, "2014-01-01");
//      strcpy(tweet1.HashTag, "1");
//      strcpy(tweet1.IDSentimentAnalysis, "1");



      //insertTweet(tweet1);
      // llenar la struct tweet

        j++;
        break;
   }


   fclose(entrada);
   puts("eso es todo el archivo");

   return EXIT_SUCCESS;
}

如果我不是一直在寻找更好的解释,希望我能说到点子上。 干杯。

【问题讨论】:

  • 似乎是时候开始使用调试器逐行检查所有相关变量以查看真正发生了什么。

标签: c string file split


【解决方案1】:

这很奇怪... 你声明 str (第 77 行):

char str[200];

然后你将 strtok 应用于 str 上的垃圾值(因为你没有初始化它)...(第 79 行)

char *  p    = strtok (str, "|");

然后你在没有正确初始化变量的情况下使用 p(第 101 行):

    while (p) {

也许问题出在某个地方?

============================================== ==

编辑:

首先,您似乎正在尝试将 linea 保存在 str 中,因此,您需要将 str 的声明更改为:

char str[LONG_MAX_LINEA];

因为您需要确保目标字符串有足够的空间。

那么你不能尝试分配做str[j] = linea;这是错误的! 因此该行应更改为:

strcpy(str,linea);

其次,对垃圾值做strtok没有意义,所以将p声明改为:

char *  p    = NULL;

然后,在此之前,你写:

p = strtok (str, "|");

现在可以用了吗?

【讨论】:

  • 我不知道真的有点卡住了,有些沮丧,在源代码的链接中,只有拆分部分有效,但是当我尝试将源代码组合到源代码时拆分和读取文件的那个我不能,也许从一开始就是一个错误的方法,但主要是我试图在拆分每个读取的行和读取后读取文件,拆分每一行将其保存到结构和调用一个函数插入 bd,如果有更好的解决方案我想知道
  • 我想我没有提到,但两个代码都应该独立工作,一个拆分给定的字符串,另一个插入数据库,就在我尝试加入两个代码时,我没有'不明白哪里做错了,而且在 C 中没有经验
  • 这就是我的回答!你声明“char str[200];”,因为你没有初始化它,它包含垃圾值。然后将 strtok 应用于垃圾并将其分配给 p(显然是错误的)。然后你在你的时候使用这个值。您应该将 strtok 应用于从文件中读取的内容...
  • 是的,你是完全正确的,我正在查看代码,它就在那里,我没有正确拆分。我真的很困惑,但现在它已经解决了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 2013-07-23
  • 1970-01-01
相关资源
最近更新 更多