0

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
cafej
  • 85
  • 1
  • 3
  • 13

2 Answers2

2

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

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

C's fopen has signature:

FILE* fopen(const char *filename, const char *mode)

when you call with i in myWrite you are telling it a string is located at that address, where likely there is garbage. If this isn't homework explain and I can elaborate but in case it is I'll just point you to itoa.

Luis
  • 1,210
  • 2
  • 11
  • 24
  • 1
    Ed's answer is better; `itoa` is not a standard function! – Al.Sal Aug 28 '14 at 16:51
  • Yes, this is homework, but i've been trying hard, and I just want to know how to name my files something like 0.txt , 1.txt 2.txt etc.... – cafej Aug 28 '14 at 16:53