Multiple file program - c

Following code is meant to read values and save them to an array. Just that when I build and run my code my file isn't found. I'm basically trying to make a program that takes a data point from a file and inputting it into my code. When it runs it shows that the file isn't found though correctly inputting the file name.
#include <stdio.h>
#include <stdlib.h>
//function prototype
void calc_results(int time[], int size);
void read_temps(int temp[]);
//set size of array as global value
#define SIZE 25
int main ()
{
rand();
//Declare temperature array with size 25 since we are going from 0 to 24
int i, temp[SIZE];
read_temps(temp);
//Temperature for the day of October 14, 2015
printf("Temperature conditions on October 14, 2015:\n");
printf("\nTime of day\tTemperature in degrees F\n\n");
for (i = 0; i < SIZE; i++)
printf( "%d \t\t%d\n",i,temp[i]);
//call the metod calc_results(temp, SIZE);
calc_results(temp, SIZE);
//pause the program output on console until user enters a key
system ("PAUSE"); return 0;
}
/**The method read_temps that takes the input array temp
and prompt user to enter the name of the input file
"input.txt" and then reads the tempertures from the file
for 24 hours of day */
void read_temps(int temp[])
{
char fileName[50];
int temperature;
int counter=0;
printf("Enter input file name : ");
//prompt for file name
scanf("%s",fileName);
//open the input file
FILE *fp=fopen(fileName, "r");
//check if file exists or not
if(!fp)
{
printf("File doesnot exist.\n");
system ("PAUSE"); //if not exit, close the program
exit(0);
}
//read temperatures from the file input.txt until end of file is encountered
while(fscanf(fp,"%d",&temperature)!=EOF)
{
//store the values in the temp array
temp[counter]=temperature;
//incremnt the coutner by one
counter++;
}
//close the input file stream fp
fclose(fp);
}
void calc_results(int temp[], int size)
{
int i, min, max, sum = 0;
float avg;
min = temp[0];
max = temp[0];
//Loop that calculates min,max, sum of array
for (i = 0; i < size; i++)
{
if (temp[i] < min)
{
min = temp[i];
}
if (temp[i] > max)
{
max = temp[i];
}
sum = sum + temp[i];
}
avg = (float) sum / size;
//open an external output file
FILE *fout=fopen("output.txt","w");
//Temperature for the day of October 14, 2015
fprintf(fout,"Temperature conditions on October 14, 2015:\n");
fprintf(fout,"\nTime of day\tTemperature in degrees F\n\n");
//write time of day and temperature
for (i = 0; i < SIZE; i++)
{
fprintf( fout,"%d \t\t%d\n",i,temp[i]);
}
printf("\nMin Temperature for the day is : %d\n", min);
printf("Max Temperature for the day is :%d\n", max);
printf("Average Temperature for the day is : %f\n", avg);
//write min ,max and avg to the file "output.txt"
fprintf(fout,"\nMin Temperature for the day is : %d\n", min);
fprintf(fout,"Max Temperature for the day is :%d\n", max);
fprintf(fout,"Average Temperature for the day is : %f\n", avg);
//close the output file stream
fclose(fout);
}

Related

C Programming - Generating Random Numbers into a new text File and retrieving them to count the occurrences (then do statistics on the side)

My goal is to generate random numbers into a new txt file where I can retrieve the randomly generated values and count the occurrences of the values (e.g. Number 1 has appeared "x" number of times). My expected output should display an output like the example given and all the occurrences should add up to 600. There is an underline on the last bracket in my newfile() function. Thanks in advance.
First 10 lines of txt output file...
2
5
4
2
6
2
5
1
4
2
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int newfile(FILE *fp)
{
char fname[20];
printf("\nEnter the name of the file... ");
scanf("%19s",fname);//File name cannot have spaces
strcat(fname, ".txt");
fp=fopen(fname, "w");
int i, N = 600, newfile[N];
for(i=0;i<N;i++)
{
newfile[i]= ((rand() % 6)+1);
fprintf(fp,"%d\n",newfile[i]);
}
}
int main()
{
int i = 0;
FILE *fp;
do
{
newfile(fp);
i++;
}
while (i<1);
FILE* fpointer;
char filename[20];
int value = 0, result = 0, num[600] = { 0 };
float sum, mean;
printf("\nEnter the name of the file... ");
scanf("%19s",filename);
fpointer = fopen(filename, "r");
if (fpointer == NULL) {
printf("ERROR: CANNOT OPEN FILE!\n");
return -1;
}
result = fscanf(fpointer, "%d", &value);
while (result == 1)
{
{
num[value] = num[value] + 1; // num[value]++
}
result = fscanf(fpointer, "%d", &value);
}
for (int i = 0; i <= 6; i++) {
if (num[i] > 0) {
printf("Number %i has appeared %d times\n", i, num[i]);
}
}
sum = (1*(num[1])+2*(num[2])+3*(num[3])+4*(num[4])+5*(num[5])+6*(num[6]));
mean = sum / 600;
printf("\nThe mean is %f",mean);
fclose(fpointer);
return 0;
}
The main problem in your code is that you forgot to close the file inside newfile function.
So just add fclose(fp); at the end of the function.
Minor issues:
you don't need to pass fp to the function newfile. Just use a local variable.
newfile[N] is not needed at all. Simply do: fprintf(fp,"%d\n", (rand() % 6)+1);
num[600] = { 0 }; is much too large as you only use index 0 .. 6
Before doing num[value] = ... you should check that value is in the expected range, i.e. to avoid writing out of bounds.

knapsack problem data storage from table in a File C

I am trying to store data for Value, Weight and Cost from a file containing a table which contains three columns of numbers for Value, Weight and Cost. The table may vary in length (9 or 21 rows) depending on the file chosen by the user.
I am having trouble trying to store the data from this file to use in a brute force function to solve the problem.
This is what I have so far.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int nr_rows;
int i = 1;
int j = 2;
int k = 3;
int l,m,n = 0;
int budget_cost;
int weight_lim;
char file_name[50];
float c[nr_rows][3];
char stringA[20] = "objectsA.txt";
char stringB[20] = "objectsB.txt";
printf("Enter the filename containing item listing: ");
scanf("%s", &file_name);
if(strcmp(file_name,stringA)==0)
{
nr_rows = 9;
}
else if(strcmp(file_name,stringB)==0)
{
nr_rows = 21;
}
printf("The number of rows is %d", nr_rows);
float value[nr_rows], weight[nr_rows], price[nr_rows];
FILE *fpointer;
fpointer = fopen(file_name, "r");
if(!fpointer)
{
printf("The file %s could not be opened.", file_name);
return 1;
}
j=0;
while(j<nr_rows)
{
i=0; // Skip the first line
while(i<3)
{
fscanf(fpointer, "%f", &c[j][i]);
//printf("%.0f\n", c[j][i]);
if(i=1) /* Change this if statement so that 1 ,4 ,7 ,10
etc. activates*/
{
c[j][i] = v[l];
l++;
printf("%f", v[l]);
}
else if(i=2)/* Change this if statement so that 2,5,8 etc.
activates*/
{
c[j][i] = w[m];
m++;
}
else if(i=3)/* Change this if statement so that 3,6,9 etc.
activates*/
{
c[j][i] = p[n];
n++;
}
i++;
}
j++;
}
fclose(fpointer);
//1. Read carefully your file name by doing:
scanf("%s", file_name); // instead of scanf("%s", &file_name);
//2. Declare c[nr_rows][3] only after reading "nr_rows"
//3. The main "while" loop could look like this
while(j < nr_rows)
{
fscanf(fpointer, "%f %f %f", &c[j][0], &c[j][1], &c[j][2]);
}
// Then,
fclose(fpointer);

C asking for user txt file, saving in array, and outputting in txt

So I have a function built already that calculated 25 random temperatures and outputted them and had a max, min, and average feature. I'm now trying to incorporate input files and output files via txt.
I tried to do some research and plug in what I could (even if I barely understood it), can someone lend some light on my code?
int get_value(void);
void calc_results(void);
void read_temps(void);
int sum = 0;
int min = 0;
int max = 0;
int temp[25];
int i = 0; //For array loop
int j = 0; //For printf loop
float avg = 0;
void read_temps() {
char fname[128];
printf("Enter .txt file name \n");
scanf("%123s", fname);
strcat(fname, ".txt");
FILE *inputf;
inputf=fopen(fname, "w");
for (i = 0; i < 25; i++){
temp[i] = fname;
sum += temp[i];
}
}
int main () {
calc_results();
return 0;
};
void calc_results(void) {
FILE * fp;
fp = fopen("Output_temps.txt", "w+");
avg = ((sum)/(25));
max = temp[0];
for(i=1;i<25;i++){
if(max<temp[i])
max=temp[i];
};
min =temp[0];
for(i=1;i<25;i++){
if(min>temp[i])
min=temp[i];
};
fprintf("Temperature Conditions on October 9, 2015 : \n");
fprintf("Time of day Temperature in degrees F \n");
for(j=0;j<25;j++){
fprintf(" %d %d\n",j,temp[j]);
}
fprintf("Maximum Temperature for the day: %d Degrees F\n", max);
fprintf("Minimum Temperature for the day: %d Degrees F\n", min);
fprintf("Average Temperature for the day: %.1f Degrees F\n", avg);
fclose(fp);
};
There were a few errors in your code, the most critical one being it doesn't compile. If you're having issues you'll want to follow the instructions for how to make a ssce. You will get a much better response this way. Then explain clearly the specific issue you are having and what it is that is happening or not happening as opposed to what you expect.
With your code you seem to be assigning to your temp array the fname variable instead of reading in the int data from the user file.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// assuming you want a maximum of temperatures of 25
#define TEMP_NUMBER 25
// use a struct to maintain and the temparatur data in one place
// without resorting to using global variables or having functions
// that require numerous parameters.
struct temp_data {
char fname[128];
int max;
int min;
int sum;
int temps[TEMP_NUMBER];
float avg;
};
struct temp_data *temps_init(void)
{
// creates a pointer to struct temp_data to hold
// your various temparture related fields
struct temp_data *td = malloc(sizeof *td);
td->sum = 0;
td->avg = 0.0;
return td;
}
void read_temps(struct temp_data *td)
{
// in your sample code you have this set to "w", needs to be "r"
FILE *inputf = fopen(td->fname, "r");
// handle error
if (!inputf) {
perror("fopen");
exit(0);
}
for (int i = 0; i < TEMP_NUMBER; i++) {
// you were setting fname to the temparature array
// instead you need to scan the temp file
fscanf(inputf, "%d", &(td->temps[i]));
td->sum += td->temps[i];
}
}
void print_results(struct temp_data *td)
{
// a print function to separate logic
FILE *fp = fopen("Output_temps.txt", "w+");
if (!fp) {
perror("fopen");
exit(0);
}
fprintf(fp, "Temperature Conditions on October 9, 2015 : \n");
fprintf(fp, "Time of day Temperature in degrees F \n");
for(int i=0; i < TEMP_NUMBER; i++)
fprintf(fp, " %d %d\n", i, td->temps[i]);
fprintf(fp, "Maximum Temperature for the day: %d Degrees F\n", td->max);
fprintf(fp, "Minimum Temperature for the day: %d Degrees F\n", td->min);
fprintf(fp, "Average Temperature for the day: %.1f Degrees F\n", td->avg);
fclose(fp);
}
void calc_results(struct temp_data *td)
{
// do only calculations
td->avg = td->sum / TEMP_NUMBER;
td->min = td->temps[0];
td->max = td->temps[0];
for (int i=1; i < TEMP_NUMBER; i++) {
td->min = td->temps[i] < td->min ? td->temps[i] : td->min;
td->max = td->temps[i] > td->max ? td->temps[i] : td->max;
}
}
int main(int argc, char *argv[])
{
// Moved user input into the main() from read_temps()
// now read_temps() only needs to read and record the temp data
struct temp_data *td = temps_init();
printf("Enter .txt file name \n");
scanf("%123s", td->fname);
strcat(td->fname, ".txt");
read_temps(td);
calc_results(td);
print_results(td);
free(td);
return 0;
};
Using a file called sample.txt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

Read a file but avoid duplicate data

My code below reads a file in c which contains a list of students names(name and last name) and their scores, it prints the file, finds the average score, the highest score and prints the students' names who obtained the highest score. My problem is that some student's names and grades are repeated in the file. So I want to know how could I read the same file but only print a list in which there are not duplicates names and scores. So next I can update the rest of information that I am looking for(ie. average).
#define MAX 30 // Maximum number of students
#define MINRANGE 0 // range of scores
#define MAXRANGE 100
int computeMax(double stSco[], int numSt); //Gets the average and highest score
void outputBest(double number[], char nameHigh[][16], int highPl, int totalSt);
//Students with the highest score
int main()
{
double score[MAX];
char name[MAX][16];
char fileName[80];
int k, count=0, hgCt;
stream dataFile;
banner();
printf("Type the name of file you want to read\n");
scanf("%79[^\n]", fileName);
puts(" Grade Student\n");//Header
dataFile = fopen(fileName, "r");
if(dataFile == NULL){
fatal( "Cannot open %s for reading", fileName);
}
for(k=0; k < MAX; k++){
fscanf(dataFile, "%lg %16[^\n]", &score[k], name[k]);
if(feof(dataFile)) break;
if(score[k] >= MINRANGE && score[k] <= MAXRANGE){ //Score validation
printf("%6.1f %s\n", score[k], name[k]);
count++; //It counts how many students there are actually
}
else{
fatal( "There are illegal grades in file %s", fileName);
}
}
fclose(dataFile);
if(count == 0){ //Checks if file is empty
fatal( "The file %s is empty", fileName);
}
else {
hgCt = computeMax(score, count); //Stores the returned highest score
outputBest(score, name, hgCt, count);
bye();
}
return 0;
}

Reading a file in C and store data in arrays

My code below reads a file in C.It displays the file, the average score, maximum score,and the names of all the students who earned the maximum score. The exam scores(0-100 format to 1 decimal place and use a field width of columns) are stored in an array and the names(name and last name limited to 15 characters) are stored in a 2-dimensional array of characters that is parallel to the scores array. My problems are:
1) The code doesn't read(print) the file properly (I think is related to fscanf and the arrays).
2) My two functions don't print the results.
Any suggestion is appreciated, thanks.
#include "tools.h"
#define MAX 30 // Maximum number of students
int computeMax(double stSco[], int numSt); // Gets the average and highest
// score
void outputBest(double num[], char nameHg[][15], int hgPl, int totStu);
int main()
{
double score[MAX];
char name[MAX][15];
char fileName[80];
int k, count = 0, hgCt;
stream dataFile;
banner();
printf("Type the name of file you want to read\n");
scanf("%79[^/n]", fileName);
dataFile = fopen(fileName, "r");
if (dataFile == NULL)
{
fatal("Cannot open %s for input", fileName);
}
while (!feof(dataFile))
{
fscanf(dataFile, "(%lg,%s)", &score[k], &name[k]);
printf("%6.1f %s\n", score[k], name[k]);
count++; // It counts how many students there are
}
hgCt = computeMax(score, count); // Stores the value sent by the
// function
outputBest(score, name, hgCt, count);
fclose(dataFile);
bye();
return 0;
}
int computeMax(double stSco[], int numSt)
{
int k, maxScore = 0, sum = 0;
double maximum = 0, average = 0;
for (k = 0; k < numSt; k++)
{
sum += stSco[k]; // It sums all scores
if (stSco[k] > maximum)
{
maximum = stSco[k];
maxScore = k; // Stores the index of the maximum score
}
}
average = sum / numSt;
printf("The average score is %d\n", average);
printf("The maximum score is %d\n", maximum);
return maxScore;
}
void outputBest(double num[], char nameHg[][15], int hgPl, int totStu)
{
int k;
for (k = 0; k < totStu; k++)
{
if (num[k] = hgPl)
{ // It finds who has the highest score
printf("%s got the highest score\n", nameHg[k]);
}
}
}
First: scanf("%79[^/n]",fileName); should be scanf("%79[^\n]",fileName);, better to use fgets().
Second typo mistake: misspelled == by = in if() condition
if(num[k]=hgPl){ //It finds who has the highest score
// ^ = wrong
should be:
if(num[k] == hgPl){ //It finds who has the highest score
Edit:
Error in while loop..
fscanf(dataFile, "(%lg,%s)", &score[k], &name[k]);
// ^ ^ ^ remove ^
should be:
fscanf(dataFile, "%lg%14s", &score[k], name[k]);
and increment k in while loop. after printf("%6.1f %s\n", score[k], name[k]);.

Resources