Reading, translating and writing data between multiple CSV files using C - c

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", &reg[index][0],&reg[index][1],&reg[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:

Related

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.

How do I read a text file and store it in an array in C programming (values seperated by a comma)?

I need help with getting datapoints, x and y values from a txt file into two arrays.
Currently, the text file consists of 5 lines like:
0.116
0.118
0.12
0.122
0.124
This is my code:
#include <stdio.h>
#include <stdlib.h>
main(void)
{
FILE *inp; /* pointer to input file */
double item;
int cnt=0,y,d,i;
double array[300],swap;
/* Prepare files for input */
inp = fopen("testdoc.txt", "r");
/* Read each item */
while ( (fscanf(inp, "%lf", &item) == 1) && (!feof(inp)) ) {
array[cnt] = item;
cnt++;
}
for (int i = 0; i < cnt; i++)
{
printf("%lf\n",array[i]);
}
printf("The total number of inputs is %d",cnt);
fclose(inp); /* Close the files */
return (0);
}
This only reads the first half of the file, which are the x values. Of which output is
0.116000
0.118000
0.120000
0.122000
The total number of inputs is 4
However, I want to read a text file and store the values in two different arrays for x and y values.
The new text file will look like this
0.116,-0.84009
0.118,4.862
0.12,-1.0977
0.122,0.22946
0.124,3.3173
How do i go changing my code above to recognize the Y values after "," sign? And to add both into two arrays at once?
I tried compiling your code posted on pastebin and received an error because of a missing bracket in your while statement.
That's an easy fix.
The larger issue is in the condition of the while loop.
fscanf returns the number of input items converted and assigned on each call.
When you modified your code to return two values, the condition in the while loop fscanf(inp, "%lf,%lf", &v1,&v2) == 1 would fail and the loop will not be entered.
Please modify the while statement to (have included the missing "(" too)..
while ( (fscanf(inp, "%lf, %lf", &v1, &v2) == 2) && (!feof(inp)) )
and you should be good to go!!!
In addition it would be a good practice to include the return type of int for the main function.

Filter text from huge .csv files, in C

I have the raw and unfiltered records in a csv file (more than 1000000 records), and I am suppose to filter out those records from a list of files (each weighing more than 282MB; approx. more than 2000000 records). I tried using strstr in C. This is my code:
while (!feof(rawfh)) //loop to read records from raw file
{
j=0; //counter
while( (c = fgetc(rawfh))!='\n' && !feof(rawfh)) //read a line from raw file
{
line[j] = c; line[j+1] = '\0'; j++;
}
//function to extract the element in the specified column, in the CSV
extractcol(line, relcolraw, entry);
printf("\nWorking on : %s", entry);
found=0;
//read a set of 4000 bytes; this is the target file
while( fgets(buffer, 4000, dncfh)!=NULL && !found )
{
if( strstr(buffer, entry) !=NULL) //compare it
found++;
}
rewind(dncfh); //put the file pointer back to the start
// if the record was not found in the target list, write it into another file
if(!found)
{
fprintf(out, "%s,\n", entry); printf(" *** written to filtered ***");
}
else
{
found=0; printf(" *** Found ***");
}
//I hope this is the right way to null out a string
entry[0] = '\0'; line[0] ='\0';
//just to display a # on the screen, to let the user know that the program
//is still alive and running.
rawreccntr++;
if(rawreccntr>=10)
{
printf("#"); rawreccntr=0;
}
}
This program takes approximately 7 to 10 seconds, on an average, to search one entry in the target file (282 MB). So, 10*1000000 = 10000000 seconds :( God knows how much is that going to take if I decide to search in 25 files.
I was thinking of writing a program, and not going to spoon fed solutions (grep, sed etc.). OH, sorry, but I am using Windows 8 (64 bit, 4 GB RAM, AMD processor Radeon 2 core - 1000Mhz). I used DevC++ (gcc) to compile this.
Please enlighten me with your ideas.
Thanks in advance, and sorry if I sound stupid.
Update by Ali, the key information extracted from a comment:
I have a raw CSV file with details for customer's phone number and address. I have the target file(s) in CSV format; the Do Not Call list. I am suppose to write a program to filter out phone number that are not present in the Do No Call List. The phone numbers (for both files) are in the 2nd column. I, however, don't know of any other method. I searched for Boyer-Moore algorithm, however, could not implement that in C. Any suggestions about how should I go about searching for records?
EDITED
I would recommend you have a try with the readymade tools in any Unix/Linux system, grep and awk. You'll probably find they are just as fast and much more easily maintained. I haven't seen your data format, but you say the phone numbers are in the second column, so you can get the phone numbers on their own like this:
awk '{print $2}' DontCallFile.csv
If your phone numbers are in double quotes, you can remove those like this:
awk '{print $2}' DontCallFile.csv | tr -d '"'
Then you can use fgrep with the -f option, to search whether strings listed in one file are present in a second file, like this:
fgrep -f file1.csv file2.csv
or you can invert the search and search for strings NOT present in another file, by adding the -v switch to fgrep.
So, your final command would probably end up like this:
fgrep -v -f <(awk '{print $2}' DontCallFile.csv | tr -d '"') file2.csv
That says... search, in file2.csv for all strings not present (-v option) in column 2 of file "DontCallFile.csv". If you want to understand the bit in <() it is called process substitution and it basically makes a pseudo-file out of the result of running the command inside the brackets. And we need a pseudo-file because fgrep -f expects a file.
ORIGINAL ANSWER
Why are you using fgetc() anyway. Surely you would use getline() like this:
while(getline(myfile,line ))
{
...
}
Are you really reading the whole "target" file from the start for every single line in your main file? That will kill you! And why are you doing it in chunks of 4,000 bytes? And what if one of your strings straddles the 4,000 bytes you compare it with - i.e. the first 8 bytes are in one 4k chunk and the last however many bytes are in the nect 4k chunk?
I think you will get better help on here if you take the time to explain properly what you are trying to do - and maybe do it with awk or grep (at least figuratively) so we can see what you are actually trying to achieve. Your decription doesn't mention the "target" file you use in the code, for example.
You can do this with awk, like this:
awk -F, '
FNR==NR {gsub(/"/,"",$2);dcn[$2]++;next}
{gsub(/ /,"",$2);if(!dcn[$2])print}
' DontCallFile.csv x.csv
That says... the field separator is a comma (-F,). Now read the first file (DontCallFile.csv) and process according to the part in curly braces after FNR==NR. Remove the double quotes from around the phone number in field 2, using gsub (global substitution). Then increment the element in the associative array (i.e. hash) as indexed by unquoted field 2 and then move to next record. So basically, after file "DontCallFile.csv" is processed, the array dcn[] will hold a hash of all the numbers not to call (dcn=dontcallnumbers). Then, the code in the second set of curly braces is executed for each line of the second file ("x.csv"). That says... remove all spaces from around the phone number in field 2. Then, if that phone number is not present in the array dcn[] that we built earlier, print the line.
Here is one idea for improvement...
In the code below, what's the point in setting line[j+1] = '\0' at every iteration?
while( (c = fgetc(rawfh))!='\n' && !feof(rawfh))
{
line[j] = c; line[j+1] = '\0'; j++;
}
You might as well do it outside the loop:
while( (c = fgetc(rawfh))!='\n' && !feof(rawfh))
line[j++] = c;
line[j] = '\0';
My advice is the following.
Put all don't call phone numbers into an array.
Sort this array.
Use binary search to check if a given phone number is among the sorted
don't call numbers.
In the code below, I just hard-coded the numbers. In your application, you will have to replace that with the corresponding code.
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare(const void* a, const void* b) {
return (strcmp(*(char **)a, *(char **)b));
}
int binary_search(const char** first, const char** last, const char* val) {
ptrdiff_t len = last - first;
while (len > 0) {
ptrdiff_t half = len >> 1;
const char** middle = first;
middle += half;
if (compare(&*middle, &val)) {
first = middle;
++first;
len = len - half - 1;
}
else
len = half;
}
return first != last && !compare(&val,&*first);
}
int main(int argc, char** argv) {
size_t i;
/* Read _all_ of your don't call phone numbers into an array. */
/* For the sake of the example, I just hard-coded it. */
char* dont_call[] = { "908-444-555", "800-200-400", "987-654-321" };
/* in your program, change length to the number of dont_call numbers actually read. */
size_t length = sizeof dont_call / sizeof dont_call[0];
qsort(dont_call, length, sizeof(char *), compare);
printf("The don\'t call numbers sorted\n");
for (i=0; i<length; ++i)
printf("%lu %s\n", i, dont_call[i]);
/* For each phone number, check if it is in the sorted dont_call list. */
/* Use binary search to check it. */
char* numbers[] = { "999-000-111", "333-444-555", "987-654-321" };
size_t n = sizeof numbers / sizeof numbers[0];
printf("Now checking if we should call a given number\n");
for (i=0; i<n; ++i) {
int should_call = binary_search((const char **)dont_call, (const char **)dont_call+length, numbers[i]);
char* as_text = should_call ? "no" : "yes";
printf("Should we call %s? %s\n",numbers[i], as_text);
}
return 0;
}
This prints:
The don't call numbers sorted
0 800-200-400
1 908-444-555
2 987-654-321
Now checking if we should call a given number
Should we call 999-000-111? yes
Should we call 333-444-555? yes
Should we call 987-654-321? no
The code is definitely not perfect but it is sufficient to get you started.
The problem with your algorithm is complexity. You approach is O(n*m) where n is number of customers and m is number of do_not_call records (or size of file in your case). You need reduce this complexity. (And Boyer-Moore algorithm would not help there which suggested by Ali. It would not improve asymptotic complexity but only constant.) Even binary search as Ali suggest in his answer is not best. It would be O((n+m)*log m). We can do better. Nice solutions are using fgrep and awk as suggested by Mark Setchell in his answers. (I would chose one using fgrep which should perform better I guess but it is only guess.) I can provide one similar solution in Perl which will provide more robust CSV parsing and should handle your data sizes in easy on decent HW. This type of solutions has complexity O(n+m).
#!/usr/bin/env perl
use strict;
use warnings;
use autodie;
use Text::CSV_XS;
use constant PHN_COL_DNC => 1;
use constant PHN_COL_CUSTOMERS => 1;
die "Usage: $0 dnc_file [customers]" unless #ARGV>0;
my $dncfile = shift #ARGV;
my $csv = Text::CSV_XS->new({eol=>"\n", allow_whitespace=>1, binary=>1});
my %dnc;
open my $dnc, '<', $dncfile;
while(my $row = $csv->getline($dnc)){
$dnc{$row->[PHN_COL_DNC]} = undef;
}
close $dnc;
while(my $row = $csv->getline(*ARGV)){
$csv->print(*STDOUT, $row) unless exists $dnc{$row->[PHN_COL_CUSTOMERS]};
}
If it would not meet our performance expectation you can go down to C road but I would definitely recommend use some good csv parsing and hashmap libraries. I would try libcsv and khash.h

Error In C File Handling

I am making a quiz program in c for a school project.I was storing question and answers in a text file.The text file contains 1 question and followed by 4 choices and a correct answer(each in a new line) and so on.The code for file handling is
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<process.h>
void main()
{
int tnum=2,mnum;
printf("Enter a file name to load the quiz from or enter dhruv.txt to load the default file\n");
printf("(For type of file and arrangement of data in it, refer to the documentation\n");
printf("WARNING: An improper quiz file may result in malfunctioning of the program.\n");
char quizfile[100];
scanf("%s",quizfile);
FILE *dj;
dj = fopen(quizfile,"r");
int test = 1;
while(dj == NULL)
{
printf("Requested file does not exist.Please enter a valid name\n");
scanf("%s",quizfile);
dj = fopen(quizfile,"r");
test++;
if(test == 5)
{
exit(0);
}
}
char line[500];
char ques[20][500],ansa[20][500],ansb[20][500],ansc[20][500],ansd[20][500],anse[20][500];
int start = 1,quesval=1,ans1=1,ans2=1,ans3=1,ans4=1,ans5=1;
while(fgets(line,sizeof line,dj) != NULL)
{
if((start%6) == 1)
{
strcpy(ques[quesval],line);
quesval++;
}
if((start%6) == 2)
{
strcpy(ansa[ans1],line);
ans1++;
}
if((start%6) == 3)
{
strcpy(ansb[ans2],line);
ans2++;
}
if((start%6) == 4)
{
strcpy(ansc[ans3],line);
ans3++;
}
if((start%6) == 0)
{
strcpy(anse[ans5],line);
ans5++;
}
if((start%6) == 5)
{
strcpy(ansd[ans4],line);
ans4++;
}
start++;
}
fclose(dj);
printf("Quiz file successfully loaded\n");
printf("/t/t WELCOME TO THE QUIZ\n\n");
printf("Every team must select one of the four correct answers to the asked questions to gain points\n");
printf("Wrong answer will not be penalized\n");
for(int k =1;k<quesval;k++)
{
int myvar;
myvar = k%tnum;
if(myvar == 0)
{
myvar = tnum;
}
printf("Question for TEAM %d\n\n",myvar);
printf("%s \n A.%s B.%s C.%s D.%s\n",ques[k],ansa[k],ansb[k],ansc[k],ansd[k]);
}
getch();
}
The problem is
if((start%6) == 0)
{
strcpy(anse[ans5],line);
ans5++;
}
The program shows File does not exist if i use this but as soon as i comment it out the program works fine.I don't know what the error is.Please do help
EDIT:My text file looks like:
Who is the owner
dhruv
jain
kalio
polika
dhruv
who is his friend
sarika
katrina
jen
aarushi
aarushi
where is he
home
office
college
toilet
office
where will he go
home
office
college
toilet
home
EDIT
I am using Turbo c++ in windows 7 using DOSBOX..The script is updated above
It's difficult to say without seeing your input file, but I suspect that your array declarations are backwards. For example, you have:
char ques[500][20];
This declares an array of 500 elements, where each element can be up to 20 characters. You probably want:
char ques[20][500];
This declares an array of 20 elements, where each element can be up to 500 characters.
If your input file contains lines longer than 20 characters, then your current code is likely overwriting your arrays.
There are several problems here but your immediate problem is this:
strcpy(anse[ans5],line);
(And all the other strcpy calls like it.)
You are copying line to the array beginning at anse[1][0]. If line contains more than 20 characters, it will overwrite memory past the end of anse. For example, if line contains 25 characters, you'll be putting it in anse[1][0] through anse[1][24]. Unfortunately anse[1][24] does not exist because anse is only 20 characters long. If any question exceeds 20 characters, you'll be corrupting memory and possibly causing a crash. Let me guess: Question 5 is longer than 19 characters, right?
In short, you have your rows and columns mixed up in your declarations. I think you wanted to allow 20 questions of 500 characters each, but you're actually allowing 500 questions of 20 characters each.
Next problem: In C, arrays are zero-based, not one-based. The first string in ques, for example, is ques[0], not ques[1].
To simplify this, think of two-dimensional arrays as a table composed of rows and columns. For example, declare a 3x4 array named foo:
char foo[3][4];
Picture it like this:
0 1 2 3
0 . . . .
1 . . . .
2 . . . .
What I have is an array of three character strings, each 4 characters long. The first string in my array is at foo[0]. The first character of the first string is at foo[0][0]. The second character is at foo[0][1], the second character of the third string is foo[2][1], and so on.
To solve this, your declarations should look like this:
char ques[20][500],ansa[20][500],ansb[20][500],ansc[20][500],ansd[20][500],anse[20][500];
int start = 1,quesval=0,ans1=0,ans2=0,ans3=0,ans4=0,ans5=0;
When you get it working, you should then ask yourself why you're testing the value of start six times each pass through the loop when it only changes once. There's a much better solution available here. Consider a three-dimensional array like this:
char answers[20][500][5];
That gives you 20 questions with 5 answers each.

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