Viết chương trình tạo một file chứa các số nguyên có tên SONGUYEN.INP. Sau đó đọc file SONGUYEN.INP và ghi các số chẵn vào file SOCHAN.OUT và những số lẻ vào file SOLE.OUT.
/************************************************************/
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
bool WriteFile();
bool SplitFile();
#define MAX_LEN 100
void main()
{
if (!WriteFile())
{
goto EXIT;
}
if (!SplitFile())
{
goto EXIT;
}
printf("\nSucessfull!!!");
EXIT:
getch();
}
/************************************************************
* Function: WriteFile()
* Description: Generate randomize number by using rand(), then
write to binary file SONGUYEN.INP
* Return: true if write successfully, false if write fail
*************************************************************/
bool WriteFile()
{
FILE *fp = NULL;
int idx;
int buff[MAX_LEN];
fp = fopen("D:\\SONGUYEN.INP", "wb");
if (!fp)
{
printf("\nError in opening file");
return false;
}
//Generate randomize number
for (idx = 0; idx < MAX_LEN; idx++)
{
buff[idx] = rand();
}
// Write data to SONGUYEN.INP file
if (fwrite(buff, sizeof(buff), 1, fp) < 1)
{
printf("\nError in writing SONGUYEN.INP file");
fclose(fp);
return false;
}
fclose(fp);
return true;
}
/************************************************************
* Function: SplitFile()
* Description: Read data from SONGUYEN.INP, then save odd number
to SOLE.OUT and save even number to SOCHAN.OUT
* Return: true if read and write successfully, false if read/write fail
*************************************************************/
bool SplitFile()
{
FILE *fp;
FILE *fpOdd, *fpEven;
int arr[MAX_LEN];
int idx;
fp = fopen("D:\\SONGUYEN.INP", "rb");
if (!fp)
{
printf("\nError in opening file");
return false;
}
if (fread(arr, MAX_LEN*sizeof(int), 1, fp) < 1)
{
printf("\nError in reading file");
fclose(fp);
return false;
}
fclose(fp);
fpOdd = fopen("D:\\SOLE.OUT", "w");
if (!fpOdd)
{
printf("\nError in opening file");
return false;
}
fpEven = fopen("D:\\SOCHAN.OUT", "w");
if (!fpEven)
{
printf("\nError in opening file");
return false;
}
for (idx = 0; idx < MAX_LEN; idx++)
{
if (arr[idx]%2 == 0)
{
fprintf(fpEven, "%d\t", arr[idx]);
}
else
{
fprintf(fpOdd, "%d\t", arr[idx]);
}
}
fclose(fpOdd);
fclose(fpEven);
return true;
}
Leave a Reply