I'm new to C programming. I just figured out how to read csv files into C by struct, but struggling to convert the script into a function, then call this function in int main(). I'll need to read loads of csv files so a function will be very helpful.
Here is my code which runs successfully (non-function version):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXROWS 2
struct cudaScenarioStruct{
char *type;
int trial;
int yPC;
int yPE;
int n;
};
struct cudaScenarioStruct cudaScenario[MAXROWS];
int main(){
int rowIndex = 0;
char line[128];
char* token = NULL;
FILE* fp = fopen("C:/Users/ms710557/Desktop/cudaScenario1(2).csv","r");
if (fp != NULL){
while (fgets( line, sizeof(line), fp) != NULL && rowIndex < MAXROWS){
cudaScenario[rowIndex].type = malloc(2);
token = strtok(line, ",");
strcpy(cudaScenario[rowIndex].type, token);
token = strtok(NULL, ",");
cudaScenario[rowIndex].trial = atoi(token);
token = strtok(NULL, ",");
cudaScenario[rowIndex].yPC = atoi(token);
token = strtok(NULL, ",");
cudaScenario[rowIndex].yPE = atoi(token);
token = strtok(NULL, ",");
cudaScenario[rowIndex].n = atoi(token);
rowIndex++;
}
fclose(fp);
}
for (int i = 0; i < MAXROWS; ++i){
printf("%s, %i, %i, %i, %i \n", cudaScenario[i].type, cudaScenario[i].trial, cudaScenario[i].yPC, cudaScenario[i].yPE, cudaScenario[i].n);
}
return 0;
}
The results look like this:
NI, 1, 61, 55, 80
NI, 2, 54, 59, 80
However when I convert it into a function and include the function in int main(), it's just not working... I've been googling for hours and couldn't find out why. This is my attempt:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXROWS 2
struct cudaScenarioStruct{
char *type;
int trial;
int yPC;
int yPE;
int n;
};
struct cudaScenarioStruct *readCudaScenarioData(){
struct cudaScenarioStruct csvData[MAXROWS];
int rowIndex = 0;
char line[128];
char* token = NULL;
FILE* fp = fopen("C:/Users/ms710557/Desktop/cudaScenario1(2).csv","r");
if (fp != NULL){
while (fgets( line, sizeof(line), fp) != NULL && rowIndex < MAXROWS){
csvData[rowIndex].type = malloc(2);
token = strtok(line, ",");
strcpy(csvData[rowIndex].type, token);
token = strtok(NULL, ",");
csvData[rowIndex].trial = atoi(token);
token = strtok(NULL, ",");
csvData[rowIndex].yPC = atoi(token);
token = strtok(NULL, ",");
csvData[rowIndex].yPE = atoi(token);
token = strtok(NULL, ",");
csvData[rowIndex].n = atoi(token);
rowIndex++;
}
fclose(fp);
}
return csvData;
}
int main()
{
struct cudaScenarioStruct *cudaScenario;
cudaScenario = readCudaScenarioData();
for (int i = 0; i < MAXROWS; ++i){
printf("%s, %i, %i, %i, %i \n", cudaScenario[i].type,
cudaScenario[i].trial, cudaScenario[i].yPC, cudaScenario[i].yPE,
cudaScenario[i].n);
}
return 0;
}
Any help will be highly appreciated!