You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C程序写入超2GB文件时无法终止的问题求助

问题分析与解决方案:生成大文件时无限循环的问题

核心问题

你的代码里循环变量i是32位int类型,而目标文件大小size是long long类型。32位int的最大值是2147483647(约2GiB),当你设置的size超过这个数值时,i会因为整数溢出变成负数,此时i < size的条件永远成立,循环就会无限运行下去。

另外还有两个可优化点:

  • password变量定义后未被使用,属于冗余代码。
  • 每次循环调用strlen(chars)会重复计算字符集长度,拖慢性能,应该提前计算好并存储。

修改后的代码

#define _FILE_OFFSET_BITS 64
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main(){
    // 将循环变量i改为long long类型,匹配size的类型
    long long i = 0;
    char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_-+={[]}\\|;:'\",<.>/?`~!@#$^&*()";
    // 提前计算字符集长度,避免重复计算
    const int char_count = strlen(chars);
    long long size;
    char keypath[512];
    
    printf("Where should the key be saved? ");
    fgets(keypath, sizeof(keypath), stdin);
    keypath[strcspn(keypath, "\n")] = 0;
    
    printf("How long should the key be? ");
    scanf("%lli",&size);
    getchar();
    
    srand((unsigned int)(time(NULL)));
    FILE* fptr = fopen(keypath,"a");
    if (fptr == NULL) {
        printf("Failed to open file for writing\n");
        return 1;
    }
    
    for (i = 0; i < size; i++){
        int choice = rand() % char_count;
        fprintf(fptr, "%c", chars[choice]);
    }
    
    fclose(fptr); 
    return 0;
}

额外建议

  1. 若追求更高写入性能,可考虑批量写入(比如每次生成一个缓冲区的字符,再一次性写入文件),减少fprintf的调用次数——单字符写入的IO开销很高。
  2. 32位Raspbian系统下,_FILE_OFFSET_BITS 64的定义已确保文件偏移量支持64位,能处理超过2GiB的文件,这部分你的代码是正确的。

内容的提问来源于stack exchange,提问作者Nicholas Picklas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:23:07