gpt4 book ai didi

c - 在 C 中解析大文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:54:40 25 4
gpt4 key购买 nike

对于一个类(class),我被赋予了使用 pthreads、openmp 和 MPI 并行编写基数排序的任务。在这种情况下,我选择的语言是 C——我不太了解 C++。

无论如何,我打算读取文本文件的方式会导致大约 500MB 文件大小的段错误。文件以行分隔的 32 位数字:

12351
1235234
12
53421
1234

我知道C,但我不太了解;我使用我知道的东西,在这种情况下,我知道的东西效率非常低。我读取文本文件的代码如下:

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

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

if(argc != 4) {
printf("rs_pthreads requires three arguments to run\n");
return -1;
}

char *fileName=argv[1];
uint32_t radixBits=atoi(argv[2]);
uint32_t numThreads=atoi(argv[3]);

if(radixBits > 32){
printf("radixBitx cannot be greater than 32\n");
return -1;
}

FILE *fileForReading = fopen( fileName, "r" );
if(fileForReading == NULL){
perror("Failed to open the file\n");
return -1;
}
char* charBuff = malloc(1024);

if(charBuff == NULL){
perror("Error with malloc for charBuff");
return -1;
}

uint32_t numNumbers = 0;
while(fgetc(fileForReading) != EOF){
numNumbers++;
fgets(charBuff, 1024, fileForReading);
}

uint32_t numbersToSort[numNumbers];

rewind(fileForReading);
int location;
for(location = 0; location < numNumbers; location++){
fgets(charBuff, 1024, fileForReading);
numbersToSort[location] = atoi(charBuff);
}

在一个包含 5000 万个数字(~500MB)的文件中,我在所有位置的倒带时遇到段错误。我对文件流的工作原理几乎一无所知。我的猜测是它试图在没有足够内存或其他东西的情况下进行 malloc,但我不知道。

所以,我在这里有两个合作伙伴:倒带段错误是如何发生的?我是不是在倒回之前做得不好,没有检查一些我应该检查的系统调用?

还有,从文本文件中读取任意数量的数字的更有效方法是什么?

感谢任何帮助。

最佳答案

我认为这里最可能的原因是(具有讽刺意味的是)堆栈溢出。您的 numbersToSort 数组分配在堆栈上,并且堆栈具有固定大小(因编译器和操作系统而异,但 1 MB 是一个典型数字)。您应该使用 malloc() 在堆(具有更多可用空间)上动态分配 numbersToSort:

uint32_t *numbersToSort = malloc(sizeof(uint32_t) * numNumbers);

不要忘记稍后释放它:

free(numbersToSort);

我还要指出,如果有任何空行,您的第一遍循环将失败,该循环旨在计算行数。这是因为在一个空行上,第一个字符是'\n'fgetc() 会消耗它;下一次调用 fgets() 将读取下一行,您将跳过计数中的空白行。

关于c - 在 C 中解析大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22101347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com