I have been working on a header file to write and edit csv files for future use. However, I cannot get this code to function properly. Albeit, this is my first time actually using object classes this way so I would like some advice and assistance in fixing the code.
hCSV.h
hCSV.cpp
main.cpp
The size function works; however, the edit function (which really should be insert but i'll change that later) doesn't.
If it helps, i tried adding
hCSV.h
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#ifndef HCSV_H
#define HCSV_H
using namespace std;
class hCSV
{
FILE *csvFile;
public:
FILE *TcsvFile;
int pos[2]; // <--- To hold x,y ie col,row
hCSV(FILE *TcsvFile);
~hCSV();
void hCSVSize(int *p[2]);
void hCSVEdit(int x, int y, int z);
};
#endif
hCSV.cpp
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class hCSV
{
FILE *csvFile;
public:
FILE *TcsvFile;
int pos[2];
hCSV(FILE *TcsvFile);
~hCSV();
void hCSVSize(int *p[2]);
void hCSVEdit(int x, int y, int z);
};
hCSV::hCSV(FILE *TcsvFile)
{
csvFile = TcsvFile;
// fprintf(csvFile, "11,12,13,14,15\n21,22,23,24,25\n31,32,33,34,35\n41,42,43,44,45\n51,52,53,54,55"); // DEBUG PURPOSES!!! should be 4 row 4 col (0, 1, 2, 3, 4)
}
hCSV::~hCSV()
{
fclose(csvFile);
}
void hCSV::hCSVSize(int *p[2]){ //<--- For example, (0,0) = A1 in excel
char temp;
int col=0, row=0, max=0;
rewind(csvFile);
do{
temp = fgetc(csvFile);
switch (temp){
case ',':
col++;
break;
case '\n':
row++;
if(col>max) max=col;
col=0;
break;
default:
break;
}
}while(temp!=EOF);
p[0] = &max; p[1] = &row; //<--- Places the address of col and row into the pointer
}
void hCSV::hCSVEdit(int x, int y, int z){
char temp;
int col=0, row=0;
fpos_t pos;
rewind(csvFile);
while(row!=y){
temp = fgetc(csvFile);
if(temp == '\n') {row++; fgetpos(csvFile, &pos);}
if((temp == EOF) && (row<y)){
fsetpos(csvFile, &pos);
for(int i=row;i<=y;i++) fprintf(csvFile, "\n");
fsetpos(csvFile, &pos);
}
}
while(col!=x){
temp = fgetc(csvFile);
if(temp == ',') {col++; fgetpos(csvFile, &pos);}
if((temp == '\n')&&(col<x)){
fsetpos(csvFile, &pos);
for(int i=col;i<=x;i++) fprintf(csvFile, ",");
fsetpos(csvFile, &pos);
}
}
fprintf(csvFile, "%d,", z); //<--- This is supposed to insert z at (x,y)
}
main.cpp
#include "hCSV.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
int main(){
hCSV ptest(fopen("test.csv", "wb+"));
int *p[2]; //<--- Declares a pointer to an integer array of size 2 (x,y) = (col,row)
ptest.hCSVSize(p);
printf("Size is: %d, %d\n\n", *p[0], *p[1]); //<--- Outputs the values at the addresses of col and row
ptest.hCSVEdit(1,1,0);
return 0;
}
The size function works; however, the edit function (which really should be insert but i'll change that later) doesn't.
If it helps, i tried adding
fprintf(csvFile, "here");to the beginning of the edit function and got a csv file with the following: \n,,E