Skip to content

Instantly share code, notes, and snippets.

@Xe
Created May 23, 2012 02:29
Show Gist options
  • Save Xe/2772918 to your computer and use it in GitHub Desktop.
Save Xe/2772918 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <assert.h>
#include "cscd240fileutil.h"
char * prompt(char * prompt);
int * makeAndFillArray(FILE * fin, int * count);
double average(int count, int * array);
int main(int argc, char ** argv) {
FILE * fin = NULL;
char * fname;
int * ara;
int count = 0;
int fdOut = -1;
int fdIn = -1;
double avg = 0.0;
/*
* this is where it opens the file
*/
if(argc > 1) {
fin = fopen(argv[1], "r");
} else {
fin = promptOpenInputFile();
}
//Open the output file with a low-level call
if(argc > 2) {
fdOut = open(argv[2], O_WRONLY | O_CREAT, 0777);
}
if(fdOut == -1) {
do {
//HACK: Dynamically allocated strings for my comfort
fname = prompt("Output filename> ");
fdOut = open(fname, O_WRONLY | O_CREAT, 0777);
free(fname);
} while (fdOut == -1);
}
//This somehow ignores the first integer in the file
fscanf(fin, "%d", &count);
//Fill the array so I can get the average
ara = makeAndFillArray(fin, &count);
avg = average(count, ara);
printf("count: %i\n", count);
//Write the average to the file in binary
write(fdOut, &count, sizeof(int));
//Close the output file
assert(close(fdOut) == 0);
fclose(fin);
return 0;
}
char * prompt(char * prompt) {
char temp[100];
printf("%s", prompt);
scanf("%s", temp);
char * ret = calloc(strlen(temp), sizeof(char));
strcpy(ret, temp);
return ret;
}
int * makeAndFillArray(FILE * fin, int * count) {
int total;
fscanf(fin, "%i", &total);
*count = total;
//printf("%d\n", total);
int * ara = (int *) malloc(*count * sizeof(int));
//printf("%s\n", ara == NULL ? "YES" : "NO");
int i, * ptr = ara;
for(i = 0; i < *count; i++) {
fscanf(fin, "%d", ptr);
ptr++;
//printf("%i\n", ara[i]);
}
//ara -= count-1;
return ara;
}
double average(int count, int * array) {
double val = 0.0;
int i = 0, * ptr = array;
for (i = 0; i < count; i++) {
val = val + *ptr;
ptr++;
}
val = val / count;
return val;
}
Display the source blob
Display the rendered blob
Raw
#ifndef CSCD240FILEUTIL_H
#define CSCD240FILEUTIL_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
FILE * openInputFile(char * fname);
FILE * promptOpenInputFile();
FILE * openOutputFile(char * fname);
FILE * promptOpenOutputFile();
#define READ "r"
#define WRITE "w"
#define MAXLINE 256
#define FNAMEMAX 100
#endif
7 7
5
32
55
4
15
22
35
LIBS=libcscd240fileutil.a
CC=gcc
NAME=dodrills
ASSIGN=lab11
#pseudo-variable FLAGS
all:
${CC} ${FLAGS} cscd240_s12_${ASSIGN}.c -o ${ASSIGN} ${LIBS}
debug:
make FLAGS=-g
package:
zip ${NAME}${ASSIGN}.zip lib/*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment