Assignment

83 views 9:59 am 0 Comments June 26, 2023

/*

SIT172 Assignment 3

Author : Hamid Khayyam

Date : 14/12/2016

Read the contents of a file into the data structure.

*/

#define _CRT_SECURE_NO_WARNINGS

#define _CRT_SECURE_NO_DEPRECATE

#include <stdio.h>

#include <stdlib.h>

#include <stdbool.h>

// Debug switch (‘1’ for debug ON, ‘0’ for debug OFF)

#define DEBUG 1

// Declared constants

// Name of file that stores our raw data

#define FILE_NAME “data-1.csv”

// Data size

#define MAX_ROWS 19

#define MAX_COLUMNS 19

// Main entry point for the program

int main(void)

{

// Declared variables

int rowIndex = 0;

int columnIndex = 0;

float rawData[MAX_ROWS][MAX_COLUMNS]; // 2-dimensional array to store our raw data

// Misc variables used for reading the data from the file

float tempfloat = 0.0F;

char newline = ‘ ‘;

// Open the file for reading

FILE *infp;

infp = fopen(FILE_NAME, “r”);

// Check for errors and exit if found

if (infp == NULL)

{

printf(“Error: failed to open %s for readingn”, FILE_NAME);

return(1);

}

// Read the file into the data structure

for (rowIndex = 0; rowIndex < MAX_ROWS; rowIndex++)

{

// Read up until the last value

for (columnIndex = 0; columnIndex < MAX_COLUMNS – 1; columnIndex++)

{

if (fscanf(infp, “%f,”, &tempfloat) != EOF)

{

rawData[rowIndex][columnIndex] = tempfloat;

}

else

{

printf(“Error: incorrect file format at row %d, col %d.n”, rowIndex + 1, columnIndex + 1);

return(1);

}

}

// Read the last value and the newline char

if (fscanf(infp, “%f%c”, &tempfloat, &newline) != EOF)

{

// Check if the last character in the line was a n otherwise an error occured

if (newline != ” && newline != ‘n’ && newline != ‘r’)

{

printf(“Error: incorrect file format at line %d. did not find a newline.n”, rowIndex + 1);

return(1);

}

else

{

rawData[rowIndex][columnIndex] = tempfloat;

}

// Reset the character before the next read

newline = ‘ ‘;

}

}

// Close the file

fclose(infp);

// Print out the raw data read from the file

if (DEBUG == 1)

{

printf(” — RAW DATA —n”);

for (rowIndex = 0; rowIndex < MAX_ROWS; rowIndex++)

{

// Read up until the last value

for (columnIndex = 0; columnIndex < MAX_COLUMNS; columnIndex++)

{

printf(“%.5f “, rawData[rowIndex][columnIndex]);

}

printf(“n”);

}

}

// Exit

return (0);

}

 

Tags: , , , , , , , , , ,