采用C语言,打印出的文本文件数组 [英] Using C, to print out an array from textFile

查看:147
本文介绍了采用C语言,打印出的文本文件数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个code,从纺织读取,然后将数据存储到内存中,打印出的屏幕,以便用户可以读取它,但它仍然是保存在内存中,以便您可以使用它的程序的其余部分。

I'm trying to create a code, which reads from textile, and then stores the data into memory, prints out to the screen so the user can read it, but it is still saved into the memory so you can use it for the rest of the program..

下面是纺织的样品

            75
            nevermind
            nvm
            not much
            nm
            no problem
            np
            people
            ppl
            talk to you later
            ttyl
            because
            cuz
            i don't know
            idk
            as soon as possible
            asap
            yeah
            ya
            how are you
            hru
            you

这样的例子不胜枚举,它总共有150个单词,151行,如果包含在第一个数字。 75用来告诉你有多少对存在。

the list goes on, it has a total of 150 words, 151 lines if the first number is included. The 75 serves to tell you how many pairs there are.

反正,这里是我到目前为止写的code,它使用这个结构

anyways, here is the code that i Have written so far, it uses this struct

            typedef struct
            {
                char *English;
                char *TextSpeak;
            }Pair;

在code到目前为止,我写的是:

The code i have written so far is:

                FILE *infile =fopen("dictionary.txt","r");

                int phraseCounter;
                fscanf(infile, "%i", &phraseCounter); //Now you have the number of phrase pairs

                //Allocate memory
                Pair *phrases=malloc(sizeof(Pair) * phraseCounter);

                //Run loop
                for(int i=0; i < phraseCounter; i++){
                    //Get the english word
                    phrases[i].English = malloc(sizeof(char));
                    fscanf(infile,"%s",phrases[i].English);

                    //run loop to read next line
                    for(int a=0; a < phraseCounter; a++){
                        phrases[i].TextSpeak = malloc(sizeof(char));
                        fscanf(infile,"%s",phrases[i].TextSpeak);
                    }
                    printf("%s - %s\n", phrases[i].English, phrases[i].TextSpeak);

                }

                fclose(infile);

                for(int i=0; i < phraseCounter; i++)
                    free(phrases[i].English);


                free(phrases);

我不断收到输出是:

The output i keep getting is:

            nevermind - atm
            by - definitely
            def - 
            - 
            - 
            - 
            - 
            - 

和它不断去为75行。

现在我不知道我是否应该使用二维数组或者如果这是可以接受的。任何帮助将AP preciated!谢谢

Now I'm not sure whether I should use a 2D array or if this will be acceptable. Any help will be appreciated! Thanks

推荐答案

有许多方法可以做到这一点。然而,一个建议,我将不得不将利用线路输入工具,如与fgets 函数getline 来使读取文件更加健壮。这是很好用的fscanf 离散变量(我把它读 phraseCounter ),但读的字符串数据未知长度/内容,线路输入真应该被使用。

There are a number of ways to do this. However, one suggestion I would have would be to make use of line-input tools such as fgets or getline to make reading the file more robust. It is fine to use fscanf for discrete variables (I left it for reading phraseCounter), but for reading string data of unknown length/content, line-input really should be used.

以下是您的code本采用的一个例子。在code被注释掉解释的逻辑。这里真正的逻辑是,你会读2线每个分配结构中的事实。使用(MOD)为切换一个简单的行计数器可以帮助您跟踪何时分配新的结构。我还添加了code接受文件名作为第一个参数的程序。 (运行,例如 ./的progname&LT;&名GT; )。让我知道如果您有任何疑问:

Below is an example of your code with this employed. The code is commented to explain the logic. The real logic here is the fact that you will read 2-lines for each allocated struct. A simple line counter using % (mod) as a toggle can help you keep track of when to allocate a new struct. I also added code to accept the filename as the first argument to the program. (to run, e.g ./progname <filename>). Let me know if you have questions:

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

#define MAXL 128

typedef struct Pair
{
    char *English;
    char *TextSpeak;

} Pair;

int main (int argc, char** argv) {

    if (argc < 2) {
        fprintf (stderr, "error: insufficient input. Usage: %s filename\n", argv[0]);
        return 1;
    }

    Pair **pair = NULL;             /* pointer to array of pointers */
    char line[MAXL] = {0};          /* variable to hold line read   */
    FILE* infile = NULL;            /* file pointer for infile      */
    unsigned int phraseCounter = 0; /* count of pairs               */
    unsigned int index = 0;         /* index to pairs read          */
    size_t nchr = 0;                /* length of line read          */
    size_t lnum = 0;                /* line number read             */

    /* open file and validate */
    if (!(infile = fopen ((argv[1]), "r"))) {
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    /* read phraseCounter */
    if (!fscanf (infile, "%u%*c", &phraseCounter)) {
        fprintf (stderr, "error: failed to read phraseCounter.\n");
        return 1;
    }

    /* allocate phraseCounter number of pointers to Pair */
    if (!(pair = calloc (phraseCounter, sizeof *pair))) {
        fprintf (stderr, "error: memory allocation failed.\n");
        return 1;
    }

    /* read each line in file */
    while (fgets (line, MAXL - 1, infile) != NULL)
    {
        nchr = strlen (line);       /* get the length of line           */

        if (nchr < 1)               /* if blank or short line, skip     */
            continue;

        if (line[nchr-1] == '\n')   /* strip newline from end           */
            line[--nchr] = 0;

        if (lnum % 2 == 0)          /* even/odd test for pair index     */
        {
            /* allocate space for pair[index]   */
            if (!(pair[index] = calloc (1, sizeof **pair))) {
                fprintf (stderr, "error: memory allocation failed for pair[%u].\n", index);
                return 1;
            }
            pair[index]-> English = strdup (line);  /* allocate space/copy to English   */
        }
        else
        {
            pair[index]-> TextSpeak = strdup (line);/* allocate space/copy to TextSpeak */
            index++;    /* only update index after TextSpeak read   */
        }

        lnum++;     /* increment line number    */
    }

    if (infile) fclose (infile);            /* close file pointer after read    */

    /* print the pairs  */
    printf ("\n Struct     English                   TextSpeak\n\n");
    for (nchr = 0; nchr < index; nchr++)
        printf (" pair[%3zu]  %-24s  %s\n", nchr, pair[nchr]-> English, pair[nchr]-> TextSpeak);

    /* free memory allocated to pair */
    for (nchr = 0; nchr < index; nchr++)
    {
        if (pair[nchr]-> English) free (pair[nchr]-> English);
        if (pair[nchr]-> TextSpeak) free (pair[nchr]-> TextSpeak);
        if (pair[nchr]) free (pair[nchr]);
    }
    if (pair) free (pair);

    return 0;
}

输入

$ cat dat/pairs.txt
10
nevermind
nvm
not much
nm
no problem
np
people
ppl
talk to you later
ttyl
because
cuz
i don't know
idk
as soon as possible
asap
yeah
ya
how are you
hru

输出

$ ./bin/struct_rd_pairs dat/pairs.txt

 Struct     English                   TextSpeak

 pair[  0]  nevermind                 nvm
 pair[  1]  not much                  nm
 pair[  2]  no problem                np
 pair[  3]  people                    ppl
 pair[  4]  talk to you later         ttyl
 pair[  5]  because                   cuz
 pair[  6]  i don't know              idk
 pair[  7]  as soon as possible       asap
 pair[  8]  yeah                      ya
 pair[  9]  how are you               hru

验证没有内存泄漏

$ valgrind ./bin/struct_rd_pairs dat/pairs.txt
==3562== Memcheck, a memory error detector
==3562== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==3562== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==3562== Command: ./bin/struct_rd_pairs dat/pairs.txt
==3562==
<snip>
==3562==
==3562== HEAP SUMMARY:
==3562==     in use at exit: 0 bytes in 0 blocks
==3562==   total heap usage: 32 allocs, 32 frees, 960 bytes allocated
==3562==
==3562== All heap blocks were freed -- no leaks are possible
==3562==
==3562== For counts of detected and suppressed errors, rerun with: -v
==3562== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

这篇关于采用C语言,打印出的文本文件数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆