5.2 Examples
Sample Code 01 (File IO)
#include <stdio.h>#include <stdlib.h>
#define BUFFER_SIZE 100
void q2() {
FILE* fp = fopen("input.txt", "r"); char zDesc[BUFFER_SIZE]; char zMonth[4]; int date, hour, minute, seconds; char zProcessName[51]; int nRead;
if (fp == NULL) { perror("File could not be opened!"); } else {
do { nRead = fscanf(fp, "%3s %d %d:%d:%d %50s", zMonth, &date, &hour, &minute, &seconds, zProcessName); fgets(zDesc, BUFFER_SIZE, fp);
if (nRead != EOF) { printf("Detials: %s %d %d:%d:%d %s\n", zMonth, date, hour, minute, seconds, zProcessName); printf("Desciption: %s", zDesc); }
} while (nRead != EOF);
fclose(fp); }
}
void print(int* pArr, int len) {
int i; printf("Printing the Array:\n"); for (i = 0 ; i < len ; i++) { printf("%d-", pArr[i]); } printf("\n");}
void q3() {
FILE* fp = fopen("input2.txt", "r"); int nRead; int len; int* pArr; int i = 0;
if (fp == NULL) { perror("File could not be opened!"); } else {
fscanf(fp, "%d", &len); pArr = malloc(sizeof(int) * len);
do { nRead = fscanf(fp, "%d", &(pArr[i])); i++;
} while (i < len && nRead != EOF);
print(pArr, len);
free(pArr); fclose(fp); }}
int main() {
q3();
return 0;}
Input File (input.txt
)
Aug 20 10:20:57 kernel: ata3: SATA link downAug 21 10:20:57 kernel2: ata3: SATA link downAug 22 10:20:57 kernel3: ata3: SATA link down
Input File (input2.txt
)
510 20 40 50 60