how to read specific value from file in c - c

if i have file contain students scores
for example this file
{
students scores :
100
90
83
70
}
how i can read just the values of scores with out reading "students scores :"???
mu code is already ok
but the problem in reading values
this is my code
#include <stdio.h>
int main (void)
{
FILE *infile;
double score, sum=0, average;
int count=0, input_status;
infile = fopen("scores.txt", "r");
input_status = fscanf(infile, "%lf", &score);
while (input_status != EOF)
{
printf("%.2f\n ", score);
sum += score;
count++;
input_status = fscanf(infile, "%lf", &score);
}
average = sum / count;
printf("\nSum of the scores is %f\n", sum);
printf("Average score is %.2f\n", average);
fclose(infile);
getch();
}

Problems I see:
input_status = fscanf(infile, "%lf", &score);
while (input_status != EOF)
is not right. The returned value of fscanf will be 0 if the read was not successful and 1 if it was successful.
More importantly, you need to add code that skips everything upto the point where you expect to see the numbers.
char line[100];
while ( fgets(line, 100, infile) != NULL )
{
// If the line containing "students scores :"
// is found, break from the while loop.
if (strstr(line, "students scores :") != NULL )
{
break;
}
}
Then, change start of the lines that read the data into:
input_status = fscanf(infile, "%lf", &score);
while (input_status == 1 )

Here's a fairly easy way to parse the file.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main (void)
{
FILE *infile;
char lineBuf[255+1];
double score, sum=0, average;
int count=0;
int fieldsParsed;
infile = fopen("scores.txt", "r");
/** Read a line from the file. **/
while(fgets(lineBuf, sizeof(lineBuf), infile))
{
/** Is the first character of the line a digit? **/
if(!isdigit(*lineBuf))
continue; /* It is not a digit. Go get the next line. */
/** Convert the number string (in lineBuf) to an integer (score). **/
score=atof(lineBuf);
printf("fields[%d] %.2f\n ", fieldsParsed, score);
sum += score;
count++;
}
average = sum / count;
printf("\nSum of the scores is %f\n", sum);
printf("Average score is %.2f\n", average);
fclose(infile);
// getch(); Non-portable
return(0);
}

Use fseek() to skip past the leading bytes to the numbers.

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 Program to get file name and range of numbers from user generate numbers from a specified range and print to file

I am writing a program to get a few things from the user and then write the results to a file. The program will get the file name, number of numbers to generate, the lowest and highest numbers to be generate, then write it all to a file that is named by the user.
The program is doing two things that are not correct:
it is generating numbers outside the user specified range
it is adding a ? to the end of the file name, I tried using strlen to remove the last character of the string but I get and error: incompatible implicit declaration of built-in function 'strlen'.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char s[100];
FILE *fout;
int i, x, len;
int h, l, q, a;
printf("Please enter the file name: ");
fgets(s, sizeof(s), stdin);
printf("How many numbers should we generate: ");
scanf("%d", &q);
printf("lowest number to generate: ");
scanf("%d", &l);
printf("Highest number to generate: ");
scanf("%d", &h);
fout = fopen(s, "wb");
a = h - l;
if ( fout == NULL)
{
printf("That file is not available\n");
exit(1);
}
fprintf(fout, "%d\n", q);
for (i=0; i < q; ++i)
{
x = (rand() % l) + a;
fprintf(fout, "%d ", x);
}
fclose(fout);
return 0;
}
concerning the file name: remove the newline character '\n' (or '\x0a') at the end of s after fgets():
if( s[strlen(s)-1] == '\n' )
s[strlen(s)-1] = '\0';
for completeness: on windows you had to remove carriage return + newline '\r'+'\n' (or '\x0d'+'\x0a')
concerning the wrong numbers: it should be x = (rand() % a) + l; (modulus range + lowest, not the other way round)

adding using file integers input

so i got the whole setup for my program and i was able to read the whole file content. the only one thing i need is to be able to add each column and put it in the variables i made. first column is miles second is gallons. so how can i make it possible using my code.
54 250 19
62 525 38
71 123 6
85 1322 86
97 235 14
#include <stdio.h>
#include <conio.h>
int main()
{
// pointer file
FILE *pFile;
char line[128];
int miles;
int gallons;
int mpg;
// opening name of file with mode
pFile = fopen("Carpgm.txt","r");
//headers
printf("Car No. Miles Driven Gallons Used\n");
//checking if file is real and got right path
if (pFile != NULL)
{
while (fgets(line, sizeof(line), pFile) != NULL)
{
int a, b, c;
if (sscanf(line, "%d %d %d", &a, &b, &c) == 3)
{
/* Values read */
printf("%d %d %d\n",a, b, c);
}
}
mpg = miles / gallons;
printf("Total miles driven: \n",miles);
printf("Total Gallons of gas: \n",gallons);
printf("Average MPG: \n",mpg);
printf("%d",a);
//closing file
fclose(pFile);
}
else
{
printf("Could not open file\n");
}
getch();
return 0;
}
That depends what you want to do.
If you just want to add values, you can do something like:
...
int miles = 0;
int gallons = 0;
...
/* Values read */
miles += b;
gallons += c;
...
Note that you can't print a like you did before closing the file as a is defined only in the while loop.
Furthermore, your printf statements won't work as expected, you forgot to specify the format %d, do:
printf("Total miles driven: %d\n",miles);
printf("Total Gallons of gas: %d\n",gallons);
printf("Average MPG: %d\n",mpg);

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;
}

Resources