[英]Writing, reading, and splitting files in C
我真的是C编程的新手,所以我需要读取一个大文件,将其每一点分割,然后将分割时得到的内容写入一个新文件,因此我必须写入多个文件,问题是当我命名新文件。 我已经在这个Proyect中工作了一个星期,但无法解决此问题。 这是我到目前为止的代码:
#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;
}
我想知道的是如何用名称中的数字来处理多个文件?
更改
myfile = fopen(i,"w");
至
char file_name[100];
sprintf(filename, "%d", i);
myfile = fopen(file_name, "w");
那应该为你解决
C的fopen具有签名:
FILE* fopen(const char *filename, const char *mode)
当您在myWrite
中用i
调用时,您告诉它在该地址处有一个字符串,该字符串中可能存在垃圾。 如果这不是功课,请解释,我可以详细阐述,但万一是正确的话,我只会指出你itoa
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.