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
1 2 |
10 1 2 -4 8 9 10 8 11 0 23 |
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ả:
1 |
Total of element: 68 |
Leave a Reply