【问题标题】:How to scan a text file and split into 4 arrays equally distributed based on number of lines如何扫描文本文件并根据行数分成 4 个均匀分布的数组
【发布时间】:2014-08-15 15:01:39
【问题描述】:

我的程序扫描一个文本文件并返回字符数、单词数和行数。我需要对其进行修改,使其能够将文本文件扫描成 4 个相等的部分。该文件将包含编号的文本文件,如 每个文件名都换行。

1_100.txt 1_101.txt 1_10.txt 1_11.txt 1_12.txt ......

大约有 240 行文件。将它们拆分为 4 个数组后,我需要创建 4 个线程,它们将对数组中的文件执行计数操作,为它扫描的每个文件(单词、字符、行)返回 3 个值。现在我只需要知道如何将原始文本文件拆分为 4 个数组,然后我需要弄清楚如何让每个线程将其数组中的值与实际文件匹配,以便可以处理其计数。

#include "Definition.h"
#include <stdio.h>
#include "ExternalVar.h"
#include <stdlib.h>
#include <string.h>

extern int Readline(),CountWord(),CountsUpdate();


char Line[MaxLine];  /* array of scanned file */
char Line2[MaxLine]; 
char Line3[MaxLine];
char Line4[MaxLine];

int NChars = 0,  /* number of characters seen so far */
    NWords = 0,  /* number of words seen so far */
    NLines = 0,  /* number of lines seen so far */
    LineLength;  /* length of the current line */ 

int wc = 0,
    lc = 0,
    cc = 0,
    tc = 0;



int i;

main(int argc, char *argv[])  
{
    FILE *fp;
    fp=fopen(argv[1],"r");

    if (fp) 
    {
        while(fgets(Line,sizeof Line,fp) != NULL)
        {

        //This is where I need to figure out how to split the array Line into 4 array with equal distribution.
            //create threads and pass each an array
            //threads return counts for their files

        cc = Readline(Line);
        NChars += cc;

        wc = CountWord(Line);
        NWords += wc;

        NLines++;

        }


    printf("Total Lines : %d \n",NLines);
    printf("Total Words : %d \n",NWords);
    printf("Total Chars : %d \n",NChars);
    fclose(fp);
    }
    return 0;  
}

【问题讨论】:

    标签: c arrays


    【解决方案1】:

    与其在读取时拆分它们,不如将它们读入一个数组并按每个文件的大小对该数组进行排序。然后以循环方式拆分大数组。这应该会改善您的总处理时间。如果您考虑分配给每个线程的文件的总大小和数量,您会做得更好。

    在任何一种情况下,您都可以使用N 索引将列表拆分为N,每个索引都保持不同列表的尾部位置:

    set all indices to 0
    for line in file:
         lists[curlist][indices[curlist]++] = line
         curlist = (curlist + 1) % N
    

    【讨论】:

    • 嘿,我试过它抛出一个错误说“ Main.c:在函数'main':Main.c:39:3:错误:未知类型名称'set'将所有索引设置为0 ^ Main.c:39:11: 错误:在 'indices' 之前预期的 '='、','、';'、'asm' 或 'attribute' 将所有索引设置为 0"跨度>
    • 这只是伪代码给你的想法。它不可能编译。
    • 好吧,你能帮我分解一下吗?我不完全理解,因为我是 C 编程新手,这实际上是我编写的第二个程序。我将整个文件扫描到一个名为“Line”的数组中。文本文件的每一行仅包含一个文本文件名,例如:1_101.txt \n 1_102.txt\n 等等。既然我已经知道该文件是 240 行,我该如何将前 60 个元素(0-59)拆分为一个新数组,并将元素(60-119)、(120-179)、(180-239)每个拆分为它们的自己的数组也是如此。您发布的伪代码说 lists[curlist][indices[curlist]++] = Line 是一个二维数组
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 2011-08-21
    • 2014-12-29
    相关资源
    最近更新 更多