I have 3 CSV files. The first of them contains 4 columns:
ID,Section1,Section2,Secion3
1,23,12,7
2,11,26,9
. . . .
. . . .
19,30,22,4
20,5,6,16
The first column is the ID and the other three contain random numbers ranging from 0 to 30.
The next file is a "conversion" file. It shows the corresponding value to each number:
30,45,44,45
29,44,42,43
28,43,42,41
. . . .
. . . .
1,22,21,22
0,20,21,21
The first column is the number to be read and the next columns are the values that will replace those numbers in each Section.
Like, if you read a 30 in Section1 it will be replaced by a 45, and if you find a 29 in Section 2 it will be replaced by a 42 and so on.
If I were to write the converted numbers into a third CSV file with the same 4 column format, how should I do it?
So far I've had no problems with generating the files since they are randomized, except for the "conversion" file, but I don't know how to proceed with the conversion.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int main (int argc,char *argv[]){
int i, num1;
char numbers[20][20];
char conversions[20][20];
//File with the initial numbers
FILE *registry = fopen("registry.csv","w+");
if (registry == NULL){
fputs ("File error",stderr);
exit (1);
}
//Conversion file
FILE *conversion = fopen("conversion.csv","r");
if (conversion == NULL){
fputs ("File error",stderr);
exit (1);
}
//File where the resulting values will be written
FILE *results = fopen("results.csv","a");
if (results == NULL){
fputs ("File error",stderr);
exit (1);
}
//Writing the headers
fprintf(results,"ID,Results1,Results2,Results3\n");
fprintf(registry,"ID,Section1,Section2,Section3\n");
srand(time(0));
//Generating the random numbers
for(i=1;i<21;i++){
sprintf(numbers[i],"%d,%d,%d,%d\n",i,rand()%31,rand()%31,
rand()%31);
fputs(numbers[i], registry);
}
//This is where I don't know how to proceed
for(i=1;i<21;i++){
sprintf(conversions[i],"%d,%d,%d,%d\n",i,
fscanf(registry,"%d,%*s,%*s,%*s\n",num1)...);
}
I was trying to do something like what I did to generate the random numbers by saving everything into a buffer and then writing it into the file and I found that the fscanf function can be of great use to skip the parts I don't need to read, but I couldn't figure out how to use it to skip the headers and the ID column and I'm still missing the conversion part.
Conversion file:
30,45,44,45
29,44,43,43
28,43,42,42
27,43,41,40
26,41,40,40
25,40,39,39
24,39,37,39
23,38,37,38
22,38,36,37
21,36,36,37
20,35,35,36
19,34,34,35
18,33,34,35
17,33,33,34
16,32,32,33
15,32,31,32
14,31,30,31
13,30,30,31
12,29,29,30
11,29,28,29
10,28,28,29
9,28,27,27
8,27,26,26
7,27,26,25
6,26,25,25
5,25,24,24
4,25,23,24
3,24,23,23
2,23,22,21
1,21,21,20
0,20,21,20
This answer is scoped to address:
//This is where I don't know how to proceed.
To do what you have described, if it is not necessary to include the first columns in registry, results or conversion for storing, then do not. Although nice for human readability, they complicate the task of reading in, and using arrays. The unused column data and header row requires array indexing gymnastics to get the data to line up correctly into the arrays.
Without the header row and numbering column, array indexes alone are sufficient to track all that is needed to make the conversion.
However, if you feel the first column/row is needed for your purposes, then adjust the array indexing of the routines shown below to accommodate.
The following steps (some of which you already do) are what I identified as essential toward making the conversion step as simple as possible...
Steps:
Create registry - 60 - random numbers (0-30) arranged in 20 rows, 3
data columns
Create int reg[20][3] = {{0}};
Read registry into reg array using a combination fgets sscanf routine.
Example:(assuming registry has already been created in your code)
registry = fopen(".\\registry.csv","r");
if (registry)
{
while(fgets(buf, sizeof(buf), registry))
{
sscanf(buf, "%d,%d,%d", ®[index][0],®[index][1],®[index][2] );
index++;
}
fclose(registry);
}
conversion table - pre-existing file
Create int conv[31][3] = {{0}};
Read conversion table into conv array using a combination fgets sscanf routine (see above example)
Once you have these arrays created properly,
Perform conversion:
Create int res[20][3] = {{0}};
Create char buf[80] = {0};
Open 'results' file: FILE *results = fopen(".\\results.csv","w");
populate results:
Example:
//File where the resulting values will be written
FILE *results = fopen(".\\results.csv","w");
if (results)
{
for(i=0;i<sizeof(reg)/sizeof(reg[0]);i++)
{
for(j=0;j<sizeof(reg[0])/sizeof(reg[0][0]);j++)
{
res[i][j] = conv[reg[i][j]][j];
// | | |___reg col == conv col
// | |______value reg == conv row
// |________________________________row and column of conv
}
sprintf(buf, "%d,%d,%d\n", res[i][0],res[i][1],res[i][2]);
fputs(buf, results);
}
fclose(results);
}
At this point, you can print the results file in a format that suits your needs.
Following is an image showing actual results using suggested approaches above for a randomly generated registry, the values you provided for conversion and resulting results. (each created without column 1 shown in your original code, as I suggested in my comments.) Image is showing indexing from 0 - n for each set of array data:
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.
hi guys i have this function to tell me how many records are in a data file.
however whenever i run it it only reads the even records
ex: if i have 0 records it outputs 0
with 1 record it outputs 0
with 2 records it ouputs 1
with 3 it outputs 1
with 4 it outputs 2
(btw its for a customer and products database project
customer is a struct and filep is the pointer to the file customerfile which is defines above this code)
im running on eclipse and can only use the gnu89/90 dialect if that makes a diff
int CusFileNumber(void)
{
customer tempcus;
filep = fopen(customersFile, "r");
fseek (filep,0,SEEK_SET);
int counter =0;
while(!feof(filep))
{
fread(&tempcus,sizeof(customer),1,filep);
printf ("%d",counter);
counter ++;
}
fclose(filep);
return (counter-1);
}
so i updated the code to get rid of the feof
it looks like this
int CusFileNumber(void)
{
customer tempcus;
filep = fopen(customersFile, "r");
fseek (filep,0,SEEK_SET);
int counter =0;
while(fread(&tempcus, sizeof(customer), 1, filep) == 1)
{
printf ("%d",counter);
counter ++;
}
fclose(filep);
return (counter);
}
but im still getting the same problem this time it isnt counting the even numbers
meaning that on every odd number counter increments by 1 but stayed the same when i have an even number of records in the file
(its a .dat file btw)
You can't use feof(3) like that. It only tells you if the stream has already ended, not that it's about to. You need to put the fread call into your loop condition and check its return value:
while (fread(&tempcus, sizeof(customer), 1, filep) == 1)
Get rid of the feof call entirely.
Are you sure sizeof(customer) matches what's really in the file?
Why are you printing counter before you increment it?
Why are you returning counter - 1 instead of counter?
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.