如何扫描文本文件并分成4个基于行数均匀分布的数组

时间:2014-06-25 06:53:49

标签: c arrays

我的程序扫描文本文件并返回字符,单词和行的数量。我需要修改它,以便它能够将文本文件扫描成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;  
}

1 个答案:

答案 0 :(得分:0)

不要在读取时拆分它们,而是将它们读入单个数组,并按每个文件的大小对此数组进行排序。然后以循环方式拆分大阵列。这应该会缩短您的总处理时间。如果考虑分配给每个线程的文件的总大小和数量,则可以做得更好。

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

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