简介
简单的文件读写。
读写文件
源代码
#include <iostream>
#include <stdio.h>
using namespace std;
/* 将矩阵写入文件
* filename: 文件名
* matrix: 矩阵首地址
* row: 矩阵的行
* col: 矩阵的列
* */
int WriteData2File(char *filename, double *matrix, int row, int col)
{
// 错误检查
if (filename == NULL)
{
printf("Null Pointer for filename! \n");
return 0x100003;
}
if (matrix == NULL)
{
printf("Null Pointer for Matrix! \n");
return 0x100002;
}
if (row < 1 || col < 1)
{
printf("Illegal Matrix Row and Column! \n");
return 0x100001;
}
FILE *wFile;
// 打开文件
wFile = fopen(filename, "wb");
// 错误检查
if (wFile == NULL)
{
printf("Error Opening the File for Null Pointer! \n");
return 0x100004;
}
else
{
// 写入文件
fwrite(matrix, sizeof(double), row * col, wFile);
// 关闭文件
fclose(wFile);
return 0;
}
}
/* 从文件中读取矩阵
* filename: 文件名
* matrix: 矩阵首地址
* row: 矩阵的行
* col: 矩阵的列
* */
int ReadDataFromFile(char *filename, double *matrix, int row, int col)
{
// 错误检查
if (filename == NULL)
{
printf("Null Pointer for filename! \n");
return 0x100003;
}
if (matrix == NULL)
{
printf("Null Pointer for Matrix! \n");
return 0x100002;
}
if (row < 1 || col < 1)
{
printf("Illegal Matrix Row and Column! \n");
return 0x100001;
}
FILE *rFile;
// 打开文件
rFile = fopen(filename, "r");
// 错误检查
if (rFile == NULL)
{
printf("Error Opening the File for Null Pointer! \n");
return 0x100004;
}
else
{
//查找文件的开头
fseek(rFile, 0, SEEK_SET);
//读取文件
fread(matrix, sizeof(double), row * col, rFile);
// 关闭文件
fclose(rFile);
return 0;
}
}
int main()
{
int iErr;
const int COL = 10;
const int ROW = 10;
char filename[1024];
// 写入文件名
sprintf(filename, "testdata/matrix%04lld.a", 1);
cout << "File Name is : " << filename <<endl;
// 初始化写入矩阵 - 测试
double *fmatrix;
fmatrix = (double*)malloc(sizeof(double) * ROW * COL);
for (int i = 0; i < COL * ROW; i++)
{
fmatrix[i] = i;
}
// 向文件写入数据
iErr = WriteData2File(filename, fmatrix, ROW, COL);
// 错误检查
if (iErr == 0)
{
cout << "Write Finished!" << endl;
}
else
{
printf("Write Error! Error Code : %x \n", iErr);
return 0;
}
// 为读入矩阵分配内存
double *rmatrix;
rmatrix = (double*)malloc(sizeof(double) * ROW * COL);
// 从文件中读入数据
iErr = ReadDataFromFile(filename, rmatrix, ROW, COL);
// 错误检查
if (iErr == 0)
{
cout << "Read Finished!" << endl;
}
else
{
printf("Read Error! Error Code : %x \n", iErr);
return 0;
}
// 验证数据
cout << "TEST MATRIX : " << endl;
for (int i=0; i < ROW; i++)
{
for (int j=0; j < COL; j++)
{
cout << rmatrix[i * COL + j] << " ";
}
cout << endl;
}
return 0;
}
编译
g++ writefile-l.cpp -o writefile-l.out