PDA

View Full Version : Read from a text file [C]


spadez
02-03-2009, 09:21 PM
Hi,

As a project I am trying to create a program in C (although I want to avoid C# and C++) which will allow me to take information from a text file (excel CSV), which will then be displayed in the program and can later be used for calculations.

Ive tried searching on the internet, but im new to this and im not sure what I should be looking for.

This is the base:

#include <stdio.h>
#include <stdlib.h>

void main(int argc, char *argv[])
{
FILE *fp; /* file pointer */
char ch;

/* see if correct number of command line arguments */
if(argc !=3)
{
printf("Usage: find &lt;filename&gt; &lt;ch&gt;\n");
exit(1);
}
fclose(fp);
}


I dont know the first thing about coding at the moment. Can someone tell me if this is usable. If it isnt, is anyone able to tell me a better solution?

Regards,

James

oesxyl
02-03-2009, 09:43 PM
start from here:


#include <stdio.h>

int main(int argc, char ** argv){
int c;
FILE * fp;

if(argc < 2){
printf("Usage:\n\t%s filename\n",argv[0]);
return -1;
}

if((fp = fopen(argv[1],"rb")) == NULL){
printf("can't open %s\n",argv[1]);
return -2;
}

while((c = fgetc(fp)) != EOF){
/* put your code to parse the csv here char by char
*/
printf("%c",c);
}

fclose(fp);
return 0;
}


best regards

spadez
02-03-2009, 10:15 PM
Hi, thank you for the code. Just to double check this is C and not C+, C++ or C#?

oesxyl
02-03-2009, 10:19 PM
Hi, thank you for the code. Just to double check this is C and not C+, C++ or C#?
yes, is c, :)
but you must write the part who get the data from you csv file, fill some data structure and do what you want to do with them.

best regards

oracleguy
02-04-2009, 01:11 AM
Hi, thank you for the code. Just to double check this is C and not C+, C++ or C#?

Just FYI: there isn't a C+, some times people think there is because of the two plus signs on C++ but there isn't.

spadez
02-04-2009, 01:29 AM
How does this code look?

#include <stdio.h>

int main(int argc, char ** argv){
int c;
FILE * fp;

if(argc < 2){
printf("Usage:\n\t%s filename\n",argv[0]);
return -1;
}

if((fp = fopen(argv[1],"rb")) == NULL){
printf("can't open %s\n",argv[1]);
return -2;
}

while((c = fgetc(fp)) != EOF){
switch (c ){
case '"':
case '\'': /* can ' start a quoted string? */
parse_a_quoted_string(c);
break;
case ',':
field_ended();
break;
case '\n':
record_ended(); /* you should also check if the last character is a '\r', if yes, it's
* to be removed
*/
break;
default:
add_a_char_to_current_field(c);

}
}
printf("%c",c);
}

fclose(fp);
return 0;
}

oesxyl
02-04-2009, 03:10 AM
use this to know how csv work:

http://www.rfc-editor.org/rfc/rfc4180.txt

try to implement a FSM inside the while:

http://en.wikipedia.org/wiki/Finite_state_machine

follow the links, there are some example and explanation.

best regards