C语言中,计算二进制文件中的整数之和可以通过多种方法来实现。可以逐个读取整数并求和,也可以一次性读取所有数据到缓冲区,然后求和,还可以逐行读取整数字符串并求和等方法。

1、逐个读取整数并求和

通过 fread 函数逐个读取文件中的整数并累加。

#include <stdio.h>

int main() {
    FILE *file = fopen("integers.bin", "rb");
    if (file == NULL) {
        perror("打开文件失败");
        return 1;
    }

    int sum = 0;
    int number;

    while (fread(&number, sizeof(int), 1, file) == 1) {
        sum += number;
    }

    fclose(file);
    printf("整数之和: %d\n", sum);

    return 0;
}

2、一次性读取所有数据到缓冲区并求和

通过一次性将文件内容读入缓冲区,减少了多次 fread 的开销。

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

int main() {
    FILE *file = fopen("integers.bin", "rb");
    if (file == NULL) {
        perror("打开文件失败");
        return 1;
    }

    fseek(file, 0, SEEK_END);
    long fileSize = ftell(file);
    fseek(file, 0, SEEK_SET);

    int *buffer = (int*)malloc(fileSize);
    if (buffer == NULL) {
        perror("内存分配失败");
        fclose(file);
        return 1;
    }

    fread(buffer, fileSize, 1, file);
    fclose(file);

    int sum = 0;
    int count = fileSize / sizeof(int);
    for (int i = 0; i < count; i++) {
        sum += buffer[i];
    }

    free(buffer);
    printf("整数之和: %d\n", sum);

    return 0;
}

3、逐行读取整数字符串并求和

如果二进制文件中的数据是以文本形式保存的(例如整数存储为字符串形式),可以逐行读取并转换为整数后求和。

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

int main() {
    FILE *file = fopen("integers.bin", "rb");
    if (file == NULL) {
        perror("打开文件失败");
        return 1;
    }

    int sum = 0;
    char line[256];

    while (fgets(line, sizeof(line), file)) {
        sum += atoi(line);
    }

    fclose(file);
    printf("整数之和: %d\n", sum);

    return 0;
}

4、使用系统调用

通过使用系统调用如read,直接从文件描述符读取数据,计算整数之和。

#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define BUFFER_SIZE 1024 
 
int main() { 
    int fd = open("integers.bin",  O_RDONLY); 
    if (fd == -1) { 
        perror("Failed to open file"); 
        return 1; 
    } 
 
    int buffer[BUFFER_SIZE]; 
    int sum = 0; 
    ssize_t bytes_read; 
    while ((bytes_read = read(fd, buffer, sizeof(buffer))) > 0) { 
        for (size_t i = 0; i < bytes_read / sizeof(int); i++) { 
            sum += buffer[i]; 
        } 
    } 
 
    close(fd); 
    printf("Sum of integers: %d\n", sum); 
    return 0; 
} 

推荐文档

相关文档

大家感兴趣的内容

随机列表