简体   繁体   English

如何读取文件并将每个readed行拆分为变量或数组

[英]how to read a file and split each readed line into variables or array

Hi all and thanks a lot in advance, what am trying to acomplish here is that am reading a file with ansi C, this file contains text and for each line contains a string like this case: 大家好,并提前多多感谢,我在这里尝试的是,我正在使用ansi C读取文件,这个文件包含文本,每行包含一个像这样的字符串:

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

and what am already doing is that am reading that file.txt and split that string into this output: 我正在做的是读取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)

so what i want to do is read the file and split the string while am reading each line and the save that value to a struct so later i can use that struct and insert into a database with another function i have. 所以我想要做的是读取文件并在读取每一行时拆分字符串并将该值保存到结构中,以便稍后我可以使用该结构并插入到具有其他功能的数据库中。 But my main issue is the spliting the string while reading each line from the file. 但我的主要问题是在从文件中读取每一行时拆分字符串。 This is the code: 这是代码:

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

Also to mention that in here i have an failed attempt to join the two codes. 另外要提到的是,在这里我尝试加入这两个代码失败了。

#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;
}

Hope i get to the point if not am constantly cheking for a better explanation. 希望我能达到目的,如果不是我不断寻求更好的解释。 Cheers. 干杯。

That's strange... You declare str (line 77): 那很奇怪......你宣布str(第77行):

char str[200];

Then you apply strtok to trash values on str (since you didn't initialize it)... (line 79) 然后你将strtok应用于str上的垃圾值(因为你没有初始化它)......(第79行)

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

Then you use p without properly initiating the variable(line 101): 然后在没有正确启动变量的情况下使用p(第101行):

    while (p) {

Maybe the problem is somewhere along there? 也许问题就在那边?

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

EDIT: 编辑:

First, it seems you are trying to save linea in str, so, you'll need to change str's declaration to this: 首先,你似乎试图在str中保存linea,所以,你需要将str的声明更改为:

char str[LONG_MAX_LINEA];

Because you need to make sure that the destination string will have enough space. 因为您需要确保目标字符串有足够的空间。

Then you can't try to assign doing str[j] = linea; 然后你不能尝试分配做str [j] = linea; this is WRONG! 这是错的! So that line should be changed to: 所以该行应改为:

strcpy(str,linea);

Second, theres no point in doing strtok to trash value, so change p declaration to: 其次,没有必要将strtok做为垃圾值,所以将p声明更改为:

char *  p    = NULL;

Then, before the while, you write: 然后,在此之前,你写道:

p = strtok (str, "|");

Does it work now? 它现在有效吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从文件中读取每一行,然后在C中将该行拆分为一个字符串和一个数组 - Read each line from a file and split the line into a string and an array in C 如何读取c中的文本文件,然后将每一行拆分为标记? - how to read a text file in c and then split each line into tokens? 如何从C中的文件中读取每一行到一个整数数组? - How to read each line into an integer array, from a file in C? 如何使用分隔符分割我从文件中读取的行并将它们存储在 C 的每个 int 变量中 - How to split line I read from file with delimiters and store them in each int variable in C 如果我打算将文件分成字符串,如何从文件中读取每一行? C - How to read each line from a file if I intend to split it up into strings? C 如何读取 C 中每一行都有数字的文件? - How to read a file with numbers on each line in C? 如何在C中将文本文件中的一行拆分为多个变量 - How to split up a line in a text file into multiple variables in C 如何在C中将逗号分隔的行从文件拆分为变量? - How to split a comma-delimited line from a file into variables in C? 将文件中每行的前3个字符读入字符串数组 - Read in first 3 characters of each line in file into an array of Strings 如何将每一行放入从 c 程序中的文件读取的数组中? - How do I put each line in an array which read from the file in c program?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM