Specific data from txt file using C - c

Hello i have a text file that contains cities, dates and temperature. How can i read temperature from specific city and day? For example if I search for Alingsås 2014-05-14 I need to get 13.81, 11.59 and 13.81. The part I am stuck with is after i have opened the file and put variables for the city and date. Info is stored in the text file like this:
Alingsås;
2014-05-14;
13.81;
11.59;
13.81;
2014-05-15;
8.89;
7.99;
9.15;
2014-05-16;
6.2;
5.07;
6.58;
2014-05-17;
7.91;
5.55;
7.91;
2014-05-18;
7.76;
5.95;
7.76;
2014-05-19;
7.95;
6.91;
9.72;
2014-05-20;
18.45;
12.92;
18.45;
Arboka;
2014-05-14;
9.55;
4.53;
10.66;
2014-05-15;
6.33;
1.5;
9.37;
2014-05-16;
8.85;
3.4;
12.08;
2014-05-17;
14.01;
4.8;
15.4;
2014-05-18;
14.16;
6.35;
17.23;
2014-05-19;
21.39;
14.57;
21.39;
2014-05-20;
23.34;
14.82;
23.34;
My Code so far is
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>
int main(void)
{
FILE * fp;
char c;
// open file
fp =fopen("C:\\Users\\Karl\\Desktop\\info.txt", "r");
if (fp != NULL)
{ char city[10] = "Ålingsås";
int temp1;
int temp2;
int temp3;
char date[13] = "2014-05-14";

One solution is to make a structure that contains the name of the city, and a pointer to another structure which will be an "array" (dynamically allocated on the heap) and where each entry contains the data and the three temperatures.
Then read one line at a time from the file, trim the input (to remove the leading and trailing whitespace, if there is any) and create the above structure. If the current line starts with a digit it's a date and read three more lines for the temperature and fill in the structure. If the current line doesn't start with a digit then you have a new city, and you create a new city-structure.

Related

fscanf returning suspicious data in C

Here is the website of the data files: Group Data Release
And here I am using the catalogs of SDSS_MTV (the third section from the bottom of the webpage).
The data are split into 8 parts. I am trying to read one of these files (such as "Fillingfactor_sdssMth12_80Mpc").
Actually, I am using fscanf() to get the data of "Fillingfactor_sdssMth12_80Mpc". Some of them show the values far greater than 1, that's unreasonable because the filing factor cannot exceed 1.
Here is the excerpt of this file (the first 5 rows):
609d 6c34 417e edb0 2664 0231 4452 3931
d948 2bb2 d877 15b2 0f5b e4b1 b646 9631
470e e3b1 06e2 3fb2 3483 f4b1 2c3d 11b2
6d86 89b1 8135 04b2 005c 44b2 d9eb a4b0
ad80 04b2 8dfb fcb1 03b0 3d32 afc6 4432
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main()
{
int i;
int Nx,Ny,Nz,itemp;
FILE *fp;
char filename[256];
sprintf(filename,"Fillingfactor_sdssMth12_80Mpc");
Nx=494;
Ny=892;
Nz=499;
float *quan = (float *)malloc(Nx*Ny*Nz*sizeof(float));
fp = fopen(filename,"r");
fread(&itemp,1,sizeof(float),fp);
// Checks the length of the table.
printf("itemp = %i\n", itemp);
if(itemp/sizeof(float) != Nx*Ny*Nz)
{
printf("error! itemp=%d\n",itemp);
exit(1);
}
for(i=0;i<Nx*Ny*Nz;i++)
{
fscanf(fp,"%f",&quan[i]);
printf("grid %i is: %.4lf\n", i, quan[i]);
}
fclose(fp);
}
Could someone explain me what is wrong?

unsorted double linked list corrupted Aborted (core dumped)

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <time.h>
typedef char string [50];
typedef struct adresse{
int zip_code;
string city;
}
adresse Fr[27381996];// I will upload data to this table from the file
int main (){
int i=-1, line_nb=1;
int j=1;
double timing=0.0;//This is for calculating the timing
//These upcoming lines are for opening the file
FILE * France_adr;
France_adr=fopen("france.csv","r");
char adr[300];
for(line_nb=1;line_nb<10;line_nb++)
{
time_t begin= time(NULL);//Here I start the timing
while((!feof(France_adr))&& (i<line_nb))
{
fgets(adr,300,France_adr);
char* s = strdup(adr);
char* val = strsep(&s,","); /* This is because in the file
there are some data that I
don't want to use and they are separated with a comma*/
while(val!=NULL)
{
val=strsep(&s,",");
// This is also to sort the data I want to get into my
table
if(j==2 && i!=-1)
{
Fr[i].zip_code=atoi(val);
printf("%d | ",Fr[i].zip_code);
}
j++;
}
i++;
j=1;
printf("\n");
}
fclose(France_adr);
printf("\n\n");
time_t end = time(NULL);
duree += (double)(1000*(end-begin));
//This section is for writing the timing and number of lines into a new
file
FILE * donnee_t;
donnee_t=fopen("Affichage_Donnee_Courbe.csv","a");
fprintf(donnee_t,"\n %d,%f",i,duree);
fclose(donnee_t);
i=0;
}
return 0;
}
I am working on this project where I have to upload huge data from a file. So what I got do is to display those lines of data on the terminal and see how much it takes for it to be displayed, and eventually creating a curve that shows how the time evolves according to the number of lines displayed (So
I write the number of lines displayed and time it took it to be displayed in another file .CSV). And since the file has 27 million line of data I thought of doing a loop for how many lines I want to display every time, But the terminal shows me that this error. I hope I explained the problem very well and I hope I can have your help. enter image description here

C - sscanf ignoring comma from csv file and reading the same piece of data twice

I am trying to read from a CSV file into struct. For some reason, the value for social security numbers is also reading the address and them the address is being read a second time into newBin.address. It looks like the sscanf is ignoring the comma that separates the socials and address when it reads the file but then does register it when it moves on reading the address. Any help is appreciated.
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#define STRSIZE 70
typedef struct BIN_DATA {
unsigned int user_number;
char name[32];
char social_security[10];
char address[32];
} BIN_DATA;
int main()
{
// Define variables.
FILE *in, *out;
char str[STRSIZE];
// New BIN.
BIN_DATA newBin;
// Open files.
in = fopen("updated.txt", "r");
// Check files.
if(in == NULL)
{
puts("Could not open file");
exit(0);
}
while(fgets(str, STRSIZE, in) != NULL)
{
memset(&newBin, '\0', sizeof(BIN_DATA));
sscanf(str, "%6u, %[^,], %[^,], %[^\n\r]", &newBin.user_number, newBin.name,\
newBin.social_security, newBin.address);
printf("%u. %s. %s. %s.\n", newBin.user_number, newBin.name,\
newBin.social_security, newBin.address);
}
return 0;
}
File being read:
289383,Estefana Lewey,591-82-1520,"9940 Ohio Drv, 85021"
930886,Burl Livermore,661-18-3839,"226 Amherst, 08330"
692777,Lannie Crisler,590-36-6612,"8143 Woods Drv, 20901"
636915,Zena Hoke,510-92-2741,"82 Roehampton St, 47905"
747793,Vicente Clevenger,233-46-1002,"9954 San Carlos St., 55016"
238335,Lidia Janes,512-92-7402,"348 Depot Ave, 29576"
885386,Claire Paladino,376-74-3432,"587 Front Ave, 32703"
760492,Leland Stillson,576-55-8588,"9793 Boston Lane, 08610"
516649,Wes Althouse,002-58-0518,"8597 Annadale Drive, 06514"
641421,Nadia Gard,048-14-6428,"218 George Street, 29150"
As mentioned in the comments, the social_security member does not allocate enough space to hold the data you're reading. It needs to be at least 12 to hold the SSN as written with a terminator at the end.
As for the format string you use with sscanf(), it's nearly correct. However, you'll want to bound the maximum string length to match what you have storage for, so for example with name of 32 you should limit it to 31 characters saving one at the end for the terminator.
I changed the social_security field to char social_security[12]; and then changed the format string to sscanf to be the following:
"%6u, %31[^,], %11[^,], %31[^\n\r]"
I was able to run the modified code with the sample input file to get the output you described. You can try it too at the link:
Runnable code

C language / How to read input from one file and write an output to another file

I am having a problem with reading input from one file and write an output to another file.
here is my code
#include <stdio.h>
#include <math.h>
//Variables declarations
FILE *reportfile;
FILE *inputfile;
char ratioName[20];
char nameorganization[25];
int asset1,asset2,asset3;
int lia1,lia2,lia3;
float asset;
float liabilites;
float ratio;
int ave_asset;
int ave_liabilites;
float ave_ratio;
char year[5]
//char currentasset[15];
//char currentLia[30];
//char tekstRatio[45];
//void
void ReadingData(void);
void DoCalcs(void);
void Report(void);
int main(void) {
ReadingData();
DoCalcs();
Report();
return 0;
}
void ReadingData(void){
inputfile = fopen("c:\\class\\current.txt" , "r");
fgets(nameorganization,25, inputfile);
fscanf(inputfile,"%d%d\n", &asset1, &lia1);
fscanf(inputfile,"%d%d\n", &asset2, &lia2);
fscanf(inputfile,"%d%d", &asset3, &lia3);
fclose(inputfile);
}
void DoCalcs(void){
ratio = asset / liabilites;
ave_asset = (asset1 + asset2 + asset3) / 3;
ave_liabilites = (lia1 + lia2 + lia3) / 3;
ave_ratio = ratio / 3;
}
void Report(void){
reportfile = fopen("c:\\class\\alimbetm_cr.txt","w");
fprintf(reportfile,"\n");
fprintf(reportfile,"Current Ratio Report",ratioName);
fprintf(reportfile,"Year");
//fprintf(reportfile,"Current Asset",currentasset);
}
//void GettingInfo(void){
//printf("Please type ratio: ");
//scanf();
//}
when I run it , it saves file to new disk but removes old data, that is NOT what I want.
What I want is read input/data from one file and write bot input/output to another file without removing input.
This is input file data (current.txt)
Hi-Tech Leisure Products
47900 31007
34500 9100
57984 14822
This how it should be on a new file
Hi-Tech Leisure Products
Current Ratio Report
Current Current Current
Year Assets Liabilities Ratio
----------------------------------------------------------
2010 47900 31007 1.54
2011 34500 9100 3.79
2012 57984 14822 3.91
----------------------------------------------------------
Average 46795 18310 3.08
This report produced by Raul Jimenez.
please help
In this case, you need to use "a" instead of "w" because write function is used to clear the old data and write the new one
The posted code does not compile! The first problem is this statement:
char year[5]
which is missing the trailing semicolon ;.
regarding:
#include <math.h>
None of the 'features' of math.h are being used in the posted code. It is a very poor programming practice to include header files those contents are not being used. Suggest removing that statement.
regarding:
reportfile = fopen("c:\\class\\alimbetm_cr.txt","w");
The mode w causes the output file to be truncated to 0 length.
Since you want to keep the old contents of the output file and simply add more data. Strongly suggest using;
reportfile = fopen("c:\\class\\alimbetm_cr.txt","a");
where the mode a will open the output file in append mode so the new data is added to the end of the existing file.
Of course, always check reportfile to assure it is not NULL (I.E. the call to fopen() was successful.
Note this statement does not compile:
fprintf(reportfile,"Current Ratio Report",ratioName);
because it has a parameter but no matching 'output format conversion' specifier. Suggest (in this case) dropping the parameter: ratioName
the calls to fopen() and fclose() are scattered all over the code. As it is currently written, only one record will be read from the input file and only one record will be written to the output file. This will be a major problem when the input file contains multiple records.
the 'desired output' indicates that the first thing should be: "Hi-Tech Leisure Products" then: "Current Ratio Report" however, there is no statement (in Report()) to actually output that second statement AND the char array ratioName[] is never set to any specific value.
the 'desired output' indicates 2 lines of column headers, etc but there is no code to actually output those column headers ( other than year ). Similar considerations exist for the data lines, the Average: line, the author line. Each datum of each line needs to be specifically output by the code, they will not 'magically' appear in the output file.
regarding;
ratio = asset / liabilites;
Neither asset nor liabilites is ever set to any specific value so they will be (due to where they are declared) containing the value(s) 0.0f. So this division will result in a DIVIDE BY ZERO crash of the code.
There are plenty more problems, but the above should get you started in the right direction.

C File Handling / Structure Problem

How does one read in a txt file containing names and marks of students and inputting them
into an array of structures.
maximum allowable records are 7:
e.g. James 45
Mary 70
Rob 100
First, define the structure. The structure describes what a record is; what data it contains. Here you have a student's name and his or her mark.
Second you need to prepare the array to write the objects of the structure into. You already know from the problem description that no more than 7 students are allowed, so you can define the length of the array to that number.
Next, open the text file.
Lastly write a loop that takes as input from the file a string for the student's name and an integer (or a floating-point point number if you so choose) for their mark. In the loop create a structure for each record and insert the structure into the array.
And of course, don't forget to close the file when you're done.
That's all there is to it. If you have any syntax or logic questions then ask in the comments, and we'll gladly help.
Read the man page for fopen: http://linux.die.net/man/3/fopen
This should give you somewhere to start.
Also, the man page for fread and fgets could be helpful. There are many ways to read from a file and the path you choose will depend on numerous things, such as the structure of the file and the amount of security you want in your application.
found this code that is similar enough that should be able to help you get done what you need.
#include <stdio.h>
#include <string.h>
/* Sample data lines
5 0 Wednesday Sunny
6 2 Thursday Wet
*/
int main() {
/* Define a daydata structure */
typedef struct {
int n_adults; int n_kids;
char day[10]; char weather[10];
} daydata ;
daydata record[30];
FILE * filehandle;
char lyne[121];
char *item;
int reccount = 0;
int k;
/* Here comes the actions! */
/* open file */
filehandle = fopen("newstuff.txt","r");
/* Read file line by line */
while (fgets(lyne,120,filehandle)) {
printf("%s",lyne);
item = strtok(lyne," ");
record[reccount].n_adults = atoi(item);
item = strtok(NULL," ");
record[reccount].n_kids = atoi(item);
item = strtok(NULL," ");
strcpy(record[reccount].day,item);
item = strtok(NULL,"\n");
strcpy(record[reccount].weather,item);
printf("%s\n",record[reccount].day);
reccount++;
}
/* Close file */
fclose(filehandle);
/* Loop through and report on data */
printf("Weather Record\n");
for (k=0; k<reccount; k++) {
printf("It is %s\n",record[k].weather);
}
}
http://www.wellho.net/resources/ex.php4?item=c209/lunches.c
Give a holler with code you tried if you have problems changing it to fit your needs.

Resources