我试图从文本文件中读取和打印文字,但程序以某种方式自行关闭。
int main(){
FILE * test= fopen("book.txt","r");
char *wp;
while(!feof(test))
{
wp=(char*)malloc(sizeof(char));
fscanf(test,"%s",wp);
printf("%s",(char)wp);
}
return;
}
答案 0 :(得分:0)
您的代码中存在很多错误,我只是想告诉您一个正确的方法。
// Include needed header files.
#include <stdio.h> // fopen, fprintf, fgets, printf, fclose
#include <stdlib.h> // exit, EXIT_FAILURE
#include <string.h> // strchr
int main(){
// Allocate more than enough space to hold a line.
char line[256];
FILE *file = fopen("book.txt","r");
// Ensure that file has opened.
if (file == NULL) {
fprintf(stderr, "Can't open file.\n");
exit(EXIT_FAILURE); // Return an integer indicating failure.
}
// Use fgets to avoid buffer overflow.
// Test for end-of-file directly with the input function.
while (fgets(line, sizeof(line), file)) {
// Remove newline if present
char *p = strchr(line, '\n');
if (p != NULL) *p = '\0';
printf("%s\n", line);
}
// Explicitly close file.
fclose(file);
return 0; // Return an integer (0 or EXIT_SUCCESS indicates success)
}