用C++设计一个类,实现对.csv文件的读写
时间: 2023-03-14 17:46:11 浏览: 126
我可以为您提供一个用C语言实现对.csv文件的读写的类的示例: #include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct CSV_data
{
char *name;
char *email;
char *phone;
};
// 功能:读取csv文件
void read_csv(char *filename, struct CSV_data *data)
{
FILE *fptr;
char name[30], email[30], phone[30];
fptr = fopen(filename, "r");
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
fscanf(fptr,"%[^,],%[^,],%[^\n]s",name,email,phone);
data->name = (char *)malloc((strlen(name)+1)*sizeof(char));
data->email = (char *)malloc((strlen(email)+1)*sizeof(char));
data->phone = (char *)malloc((strlen(phone)+1)*sizeof(char));
strcpy(data->name,name);
strcpy(data->email,email);
strcpy(data->phone,phone);
fclose(fptr);
}
// 功能:写入csv文件
void write_csv(char *filename, struct CSV_data data)
{
FILE *fptr;
fptr = fopen(filename,"w");
if(fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
fprintf(fptr,"%s,%s,%s",data.name,data.email,data.phone);
fclose(fptr);
}
阅读全文