Search code examples
cfopen

Contunue writing where I left off in a csv file in C


I need to write CSV columns and row in different code section but I can't continue where I left off

Can I do this? How can I skip the end of the document? I tried fseek() but not worked. I am putting similar code which I work on

#include <stdlib.h>
#include <stdio.h>


//function declaration
int fonit(int count);

int main(int argc, char const *argv[])
{
    int a=100;
    int b=a/10;
    
    for (int a = 0; a < 10; a++)
    {   
        // row number
        FILE *file;
        file = fopen("fant.csv", "w+");
        // fseek( file,10, SEEK_END);
        fprintf(file, "%d", a);
        fprintf(file, ",");
        fclose(file); 
            
        for (int j = 0; j < 10; j++){
            fonit(j);
        }
        
        FILE *file;
        file = fopen("ant.csv", "w+");
        // fseek( file,10, SEEK_END);
        fprintf(file, "%d", b);
        fprintf(file, ",");
        fprintf(file,"\n");
        fclose(file);
        
    }
    

    return 0;
}

int fonit(int count){
    int k=0;
    for (int i = 0; i < count; i++)
    {
        for (int j = 0; j < 100; j++)
        {
            
            k=j%2;
        }
        
    FILE *file;
    file = fopen("ant.csv", "w+");
    // fseek( file, -10,SEEK_END);
    fprintf(file, "%d", k);
    fprintf(file, ",");
    fclose(file);
    }
    return 0;
}

I am fully open to different command or C++ :)


Solution

  • When you want to append to a file instead of overwriting it ("continue where I left off"), you have to open the file in append mode instead of in write mode. Append mode appends to the file, while write mode overwrites it. So, the fix would be to change w+ in your call to fopen to a+. I recommend you to leave out the plus sign in the open mode, because, firstly, you don't read from the file at all (so don't need it), and secondly, you should not use the same file object for reading and writing, because that can lead to unexpected behaviour, because it makes it easy to get muddled with where you currently are in the file. Instead, if you have to do reading and writing, first open the file in read mode, do the reading, close it. Then, open it again in write mode, do your writing, close it.