I was attempting to read a CSV file with the readCsv()
function defined below. I happened to observe that when the readCsv()
function is called within the main()
function,
I end up experiencing a runtime error and the function readCsv()
fails to work properly. By contrast, when I instead rename the readCsv()
function to main()
(of course having commented the main()
function first), the program works perfectly. But now I'm stuck because I need to be able
to call the readCsv()
function within main()
.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int readCsv(void)
{
int n = 0;
while(n == 0)
{
do{
printf("Enter the index of the student you want to query:");
scanf("%i",&n);
while(getchar() != '\n')
{
continue;
}
}while((isdigit(n)) != 0);
}
n++;
FILE* fp;
fp = fopen("students.csv","r+");
if ((fp == NULL)) exit(1);
char buffer[1024];
int row,column = 0;
while(fgets(buffer,1024,fp))
{
column = 0;
row++;
if(row != n)
{
continue;
}
else if (row == n)
{
char* value = strtok(buffer,",");
while(value)
{
if (column == 0)
{
printf("\nIndex:");
}
if (column == 1)
{
printf("\tName:");
}
if (column == 2)
{
printf("\tAge:");
}
if (column == 3)
{
printf("\tphone:");
}
printf("%s",value);
value = strtok(NULL,",");
column++;
}
printf("\n");
break;
}
else
{
printf("None of the conditions are true");
break;
}
}
fclose(fp);
return 0;
}
void main(void)
{
readCsv();
}