Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to Read CSV from a file

Status
Not open for further replies.

kongit

Programmer
May 8, 2002
3
US
Just joined this forum :)
I need help in reading CSV like shown below using C from a file. each record is seaperated by "\n"
I know you can tell C++ to do this using fstream
I need help. thank you
sam, reynoso, samreynoso@hotmail.com, 1318144651075952
craig, lam, craiglam@yahoo.com, 2619366889742164
jeffrey, veeraraghavan, jeffreyveeraraghavan@hotmail.com, 1723729256559212
mark, bobbett, markbobbett@hotmail.com, 6672346610803161
mark, nesbitt, marknesbitt@hotmail.com, 1342147258657228
 
Here's a sample (untested)

#include <stdio.h>
#include <string.h>

#define STRIP_NEWLINE(S) do { char *tmp=strchr(S,'\n'); if (tmp) *tmp=0; } while (0)

#define MAXLINE 100 /* suit to taste */
int main(void)
{
FILE *fp=fopen(&quot;csv.txt&quot;,&quot;r&quot;);
if (!fp) {
perror(&quot;fopen&quot;);
} else {
char line[MAXLINE+1];
while (fgets(line,sizeof line,fp)) {
char *field;
int fnum;
STRIP_NEWLINE(line);
for (fnum=1,field=strtok(line,&quot;,&quot;);
field;
++fnum,field=strtok(NULL,&quot;,&quot;)) {
printf(&quot;field %d=%s\n&quot;,fnum,field);
}
}
}
return 0;
}

Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top