Search code examples
ciofile-management

Writing, reading, and splitting files in C


I'm really new at C programing, so I need to read a big file, split it every point, and write in a new file what I got when splitting, so I have to write several files, the problem is when I'm naming the new files. I've been working in this proyect like for a week and I can't fix this issue. Here the code I have so far:

#include <stdio.h>
#include <string.h>

char *myRead(char file_name[]){
    char *output;
    long size;
    FILE *myfile = fopen(file_name,"rb"); 

    fseek(myfile, 0, SEEK_END);
    size = ftell(myfile); 
    rewind(myfile);

    output = (char*) malloc(sizeof(char) * size);
    fread(output,1,size,myfile);
    fclose(myfile);

    return output;
}

void myWrite(char content[], int i){
    FILE *myfile;
    myfile = fopen(i,"w");
    fprintf(myfile,"%s",content);
    fclose(myfile); 
}

void split(char *content){
 int word_length = strlen(content);

    int i = 0;

    char *output = strtok (content,".");
    while (output != NULL){

        myWrite(output,i);
        printf("%s\n", output);
        output = strtok (NULL, ".");
        i++;
    }
}

int main(){
    char file_name[] = "hourglass.txt";
    char *content = myRead(file_name);
    split(content);
    return 0;
}

What I want to know it's how can I do several files with just a number for the name?


Solution

  • Change

    myfile = fopen(i,"w");
    

    to

    char file_name[100];
    sprintf(filename, "%d", i);
    myfile = fopen(file_name, "w");
    

    That should fix it for you