이진 파일 mydata.dat에 "this is a test"라는 문자열을 작성했습니다. 이것이 파일의 전체 내용입니다. 문자열을 다시 읽고 싶지만 출력이 표시되지 않습니다. 프로그램은 오류없이 실행됩니다. 내가 뭘 잘못하고 있는지 아십니까?
FILE *f = fopen("mydata.dat", "rb");
char content[100];
while(fread(content, sizeof(content), 1, f) == 1){
printf("%s", content);
}
fclose(f);
먼저 문자를 읽으려면 fgets()
. 정말로 fread()
.
fread()
읽은 항목 수 를 반환하므로 귀하의 경우에는 0
. fread()
100 바이트의 요소 1 개를 읽 도록 요청하기 때문에 ... 0
파일이 100 바이트 미만인 경우 항상을 반환 합니다. 요소의 크기와 요소 수를 바꿨습니다.
또한 배열이 유효한 C 문자열이되도록하려면 끝에 NULL 종료 자 바이트를 넣어야합니다. 때문에 fread()
당신을 위해 그것을 할 수 없습니다.
예:
#include <stdio.h>
int main(void) {
FILE *f = fopen("mydata.dat", "rb");
if (f == NULL) { // Error check
perror("fopen()");
return 1;
}
char content[100];
size_t ret;
// We loop on the file to read 99 bytes at each loop
// sizeof *content is the size of an element of content
while ((ret = fread(content, sizeof *content, sizeof content - 1, f)) > 0) {
content[ret] = '\0'; // We use ret to nul terminate our string
printf("%s", content);
fflush(stdout); // flush the standard output
}
fclose(f);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다