我是C编程的新手。我只是弄清楚如何通过struct将csv文件读入C,但是努力将脚本转换为函数,然后在int main()中调用此函数。我需要读取大量的csv文件,这样函数才会非常有用。
这是我的代码成功运行(非功能版本):
#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;
}
结果如下:
NI, 1, 61, 55, 80
NI, 2, 54, 59, 80
然而,当我将它转换为函数并将函数包含在int main()中时,它只是不起作用...我已经谷歌搜索了几个小时但无法找到原因。这是我的尝试:
#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;
}
任何帮助都将受到高度赞赏!