我正在尝试读取和写入文本文档,然后对其执行操作。
#include<stdio.h>
#include<string.h>
int WRITE(char *FILENAME, char *DATA)
{
FILE *ptr_file;
ptr_file =fopen(FILENAME, "w");
if (!ptr_file)
return 1;
fprintf(ptr_file,"%s", DATA);
fclose(ptr_file);
return 0;
}
char READ(char *FILENAME)
{
FILE *ptr_file;
char buf[1000];
char* ret="";
ptr_file =fopen(FILENAME,"r");
if (!ptr_file)
return "FAIL\n";
while (fgets(buf,1000, ptr_file)!=NULL)
ret=strcat("%s",ret);
fclose(ptr_file);
return ret;
}
int main()
{
char* DAT = "lol";
char* FILENAME = "output.txt";
char* NEWDAT;
int count=0;
int max=10;
while (count<max) {
NEWDAT=READ(FILENAME);
WRITE(FILENAME,strcat(DAT,NEWDAT));
count++;
}
READ(FILENAME);
return 0;
}
这就是编译器所说的
gcc -Wall -o "filewrite" "filewrite.c" (in directory: /home/x/Documents/programming/C code)
filewrite.c: In function ‘READ’:
filewrite.c:22:3: warning: return makes integer from pointer without a cast [enabled by default]
filewrite.c:26:2: warning: return makes integer from pointer without a cast [enabled by default]
filewrite.c: In function ‘main’:
filewrite.c:38:9: warning: assignment makes pointer from integer without a cast [enabled by default]
Compilation finished successfully.
然后它给我一个 Code 139/Segmentation Fault。我……真的无法理解这里发生了什么;在我所处的水平。
#回复后编辑:固定代码工作
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // malloc
int WRITE(char *FILENAME, char *DATA)
{
FILE *ptr_file;
ptr_file =fopen(FILENAME, "w");
if (!ptr_file)
return 1;
fprintf(ptr_file,"%s", DATA);
fclose(ptr_file);
return 0;
}
char* READ(char *FILENAME)
{
FILE *ptr_file;
char buf[1000];
char *ret = malloc(1);
int retsize = 1;
ret[0]='\0';
buf[0]='\0';
ptr_file = fopen(FILENAME,"r");
if (!ptr_file) {
ret = realloc(ret, strlen("FAIL\n") + 1);
strcpy(ret, "FAIL\n");
return ret;
}
while (fgets(buf,1000, ptr_file)!=NULL)
{
retsize += strlen(buf)+1; // new size is old size + length of string in buf
ret = realloc(ret, retsize); // increase the size of the allocation
strcat(ret, buf); // append the new data
}
fclose(ptr_file);
return ret;
}
int main()
{
char* DAT = malloc(1);
int datsize = 1;
char* FILENAME = "output.txt";
char* NEWDAT;
strcpy(DAT, "LOL");
int count=0;
int max=5;
while (count<max) {
NEWDAT=READ(FILENAME);
datsize += strlen(NEWDAT) + strlen(DAT);
DAT = realloc(DAT, datsize);
strcat(DAT,NEWDAT);
WRITE(FILENAME,DAT);
printf("%i\n",count);
printf("%s\n",DAT);
count++;
}
READ(FILENAME);
return 0;
}