我在使用 fwrite() 和 fread() 时遇到了一些麻烦
I have some trouble with fwrite() and fread()
#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)
#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)