Hi, I am

Ngô Tôn

I am a programmer.

Home / Programming / C/C++ / Tính tổng các phần tử trong mảng và ghi ra file

Tính tổng các phần tử trong mảng và ghi ra file

Dữ liệu vào : tập tin văn bản ARRAY.INP gồm hai dòng:
– Dòng 1 chứa số nguyên n ( n < = 10 )
– Dòng 2 chứa n số nguyên
ARRAY.INP file

Code:

/************************************************************/
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

bool ReadFile(char*);

#define MAX_LEN 100

void main()
{
char Dir[] = "D:\\ARRAY.INP";
if (!ReadFile(Dir))
{
goto EXIT;
}
EXIT:
getch();
}
/************************************************************
* Function: ReadFile()
* Description:
* Return: true if read successfully, false if read fail
*************************************************************/
bool ReadFile(char *pathFile)
{
FILE *fp = NULL;
int totalElement;
int *pBuf;
int idx;
int sum = 0;
fp = fopen(pathFile, "r");
if (!fp)
{
printf("\nError in opening file");
return false;
}
if (fscanf(fp, "%d", &totalElement) < 1)
{
printf("\nError in reading file");
return false;
}
pBuf = (int*)malloc(totalElement * sizeof(int));
if (!pBuf)
{
printf("\nError in allocate memory");
return false;
}
for (idx = 0; idx < totalElement; idx++)
{
if (fscanf(fp, "%d", &pBuf[idx]) < 1)
{
printf("\nError in reading file");
return false;
}
}
for (idx = 0; idx < totalElement; idx++)
{
sum += pBuf[idx];
}
printf("\nTotal of element: %d", sum);
if (pBuf)
{
free(pBuf);
}
return true;
}

Kết quả:

About ngoton

Ngô Tôn is a programmer with passion for tailored software solutions. Comes with 7+ years of IT experience, to execute beautiful front-end experiences with secure and robust back-end solutions.

Check Also

Xây dựng hàm bạn để tính diện tích hình chữ nhật

Yêu cầu: Xây dựng hàm bạn để tính diện tích hình chữ nhật Code: Giải …

Leave a Reply

avatar
  Subscribe  
Notify of