我有一个代码,它将txt文件的内容反向打印为字符串。我使用malloc()
函数将我的字符串的每个字符存储在txt文件中。它工作正常但它打印的内容前面有'\0'
的原因是什么?
void veriyitersyazdir(FILE *file)
{
char metin; // that gets the every single char of my string
int boyutsayac=0; // that stores my string's size
char *metinarr=NULL; // that is my malloc() array pointer
int dongusayac; // that is a counter variable that is used to print my string reversely.
system("cls");
file = fopen("C:\\metin.txt", "r");
do {
metin = fgetc(file);
if (metin==EOF) {
break;
}
boyutsayac++;
} while (1);
metinarr = (char *) malloc(sizeof(char)*boyutsayac);
fseek( file, 0, SEEK_SET);
for (dongusayac = 0; dongusayac < boyutsayac; dongusayac++) {
metin = fgetc(file);
metinarr[dongusayac]= metin;
}
fseek( file, 0 , SEEK_SET);
for (; dongusayac >=0; dongusayac--) {
printf("%c", metinarr[dongusayac]);
}
fclose(file);
}
txt文件的内容:Mustafa Mutlu
代码的输出:UltuM afatsuM
答案 0 :(得分:1)
正如bluepixy所述,你的主要问题来自你用来读取的for
循环,它比读取的字符数增加dongusayac
一个。
在for
循环中始终如此,因为它会增加变量,然后检查它是否仍然符合条件。所以最后的增加永远不适合这种情况。
这是一种更清洁的方式来做你正在做的事情:
void reverse() {
FILE *file;
size_t size;
int i;
if (!(file = fopen("c:\\metin.txt", "r"))) {
printf("error opening file\n");
exit(1);
}
fseek(file, 0L, SEEK_END);
size = ftell(file);
char *content = malloc(size); // allocate memory for the full text file
fseek(file, 0, SEEK_SET); // rewind the file cursor
fread(content, 1, size, file);
for (i = size - 1; i >= 0; i --) { // output contents in reverse order
printf("%c", content[i]);
}
fclose(file);
}