gpt4 book ai didi

c++ - 我在fwrite()和fread()上遇到了一些麻烦

转载 作者:行者123 更新时间:2023-12-02 10:32:42 25 4
gpt4 key购买 nike

#define ARRAY_SIZE 10

#include <iostream>
using namespace std;

int main()
{
// create array mas1 of ARRAY_SIZE integers and fill it with random values
int array1[ARRAY_SIZE]{ 10, 78, 23, 81, 50, 15, 24, 26, 90, 59 };

// write ARRAY_SIZE integers from array1[] to f1.txt
FILE* f1;
fopen_s(&f1, "f1.txt", "w+");
fwrite(array1, sizeof(array1[0]), ARRAY_SIZE, f1);

// read ARRAY_SIZE integers from f1.txt to array2[]
fseek(f1, 0, SEEK_SET);
int array2[ARRAY_SIZE];
fread(array2, sizeof(array2[0]), ARRAY_SIZE, f1);

// print array1
cout << "array1: ";
for (int i = 0; i < 10; i++)
{
cout << array1[i] << " ";
}
cout << endl;

// print array2
cout << "array2: ";
for (int i = 0; i < 10; i++)
{
cout << array2[i] << " ";
}
}

输出:
array1:10 78 23 81 50 15 24 26 90 59
array2:10 78 23 81 50 15 24 -858993460 -858993460 -858993460

为什么array1正常输出,而array2不正常?
我使用Visual Studio 2019

最佳答案

将您的fwrite修改为

fwrite(array1, sizeof(int), ARRAY_SIZE, f1);

并恐惧为
fread(array2, sizeof(int), ARRAY_SIZE, f1);
fclose(f1)

关于c++ - 我在fwrite()和fread()上遇到了一些麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61691116/

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