[완료]fread, fwrite 질문입니다 ㅠ

kombo67의 이미지

실행하면
배운 언어 선택 또는 추가하고
뭘 배웠는지 적는 프로그램인데

추가를 하고 다음에 다시 켰을때 그게 보존되게 하려고
데이터 저장을 진행하게 되었습니다..

일단 코드는

 while(1) {
         while (curr != NULL) {
             printf("[%d] %s\n\t%s\n", ++j, curr->name, curr->description);
             curr = curr->next;
         }
         printf("\n");
         printf("Project_1 : ");
         scanf("%d", &gotcha);
         if (gotcha == 99) {
             fp = fopen("save_data_file", "rt");
             if (fp == NULL ) {
                 perror("Cannot Save a data on File\n");
                 exit(0);
             }
             fwrite(curr, sizeof(struct NODE), sizeof(curr), fp);
             // printf("Maybe Success\n");
             fclose(fp);
 
             while(curr != false) {
                 Dellist(curr);
                 Dellist(head);
                 Dellist(&temp);
             }
             exit(0);
         } else if (gotcha == 0 ) {
             Node* now = Addlist(target, &temp);
             if ( now == NULL ) {
                 perror("리스트 추가 실패");
                 exit(0);
             }
             printf("노드를 추가했어 !\n");
             printf("어떤 언어를 추가할꺼야 ?\n");
             scanf("%s", now->name);
             getchar();
             printf("설명란에 적을꺼 있음 적으셈 [없다면 그냥 엔터쳐 ㅋㅋㅋ]\n");
             scanf("%[^\n]s", now->description);
         } else if (gotcha <= j) {
 
         }
         curr = head->next;
         j = 0;
         getchar();
     }

대강 이런식입니다.

typedef struct NODE {
struct NODE *next;
char name[20];
char description[200];
} Node;

이런식입니다
#pragma pack(push, 1) // 요놈으로 최소사이즈 맞추고
해봤는데 안되네요 ㅠㅠ ( 위 코드는 작업중인것이고 테스트 코드를 작성하여 해봤으나 .. ㅠㅠ )
테스트 코드입니다

    char *description = "리눅스 bash 스크립트, 시스템 콜 함수를 이용하여 하드웨어 쪽이나 파일을 제어할 수 있다, 물론 서버 자동화 에도 사용할 수 있다\n";
    while(1) {
           fp = fopen("save_data_file", "wb");
           if (fp == NULL ) {
 
                perror("Cannot Save a data on File\n");
                exit(0);
            }
            printf("%lu\n", sizeof(description));
            fwrite(description, 1, sizeof(description), fp);
            fclose(fp);
 
 
            exit(0);
   }
 
	FILE *fp;
	char *get;
 
 
	fp = fopen("save_data_file", "rb");
	if(fp == NULL) {
		perror("Cannot Load a file : \n");
		exit(0);
	} else {
		printf("Sueccss\n");
	}
	printf("%lu\n", sizeof(char *));
	fread(get, 1, sizeof(char *), fp); // reads an array of doubles
	puts("Array read successfully, contents: ");
	for(int n = 0; n < 1; n++) printf("%c ", get);

이걸 진행하면서 많이 검색했습니다만 마무리가 안되네요 ㅠㅠ

1. 원형을 보면 void * 를 첫번쨰 인자로 받는데
저 같은 경우는 배열을 선언하여 하는 것보단 ( 인터넷에 보면 char buf[MAXSIZE] 선언, 사이즈를 모른다는 가정하여 포인터로 해당 주소값을 바라보게 하려고 포인터 변수 선언 )
2. 2번쨰 인자로는 char 방식이여서 1씩 읽게끔 하였고 3번쨰 인자는 sizeof 로 크기를 읽어온다, 4번째는 파일 스트림
3. 제가 무엇을 놓치고 있는 걸까요 ... ?

선배님들 도움이 필요합니다...

kombo67의 이미지

우선, 두서없는 글 죄송합니다

다시 마음 잡고 천천히 살펴보고 문제 해결했습니다
코드 올립니다 ( 테스트 코드이며, 본글의 실제 코드에서는 이 글 작성 후 수정할 예정입니다 )

    while(1) {
           fp = fopen("save_data_file", "wb");
           if (fp == NULL ) {
 
                perror("Cannot Save a data on File\n");
                exit(0);
            }
            printf("%lu\n", sizeof(description)); // 여기서 description 은 char[] 입니다
            fwrite(description, 1, sizeof(description), fp);
            printf("%d", sizeof(description)); // 해본 결과 174 ( 사이즈 확인하고 )
            fclose(fp);
 
 
            exit(0);
   }
}
 
입력 파일입니다
int main() {
 
	// assign variable
	FILE *fp;
	char *get;
	int size;
	fp = fopen("save_data_file", "rb");
	if(fp == NULL) {
		perror("Cannot Load a file : \n");
		exit(0);
	} else {
		printf("Sueccss\n");
	}
	fseek(fp, 0, SEEK_END);    // 파일 포인터를 파일의 끝으로 이동시킴
	size = ftell(fp);          // 파일 포인터의 현재 위치를 얻음
	rewind(fp);        // 코드 복붙 한거라 확인해야합니다만, 다시 처음으로 돌리는 함수인듯 합니다
	printf("%d\n", size);   // 174 확인하고
	get = (char *)malloc(sizeof(char)*size);     // 메모리 할당 했습니다
	fread(get, 1, size, fp); // rweads an array of doubles   // 1바이트를 174만큼 해서 변수에 넣습니다 여기서 get 변수는 char * 형 이기떄문에
                                                                                               // void * 에 위반되지 않습니다
	// printf("%zu", ret_code);    // 이는 확인 코드인데 여기선 사용하지 않습니다 ( 지우셔도 됩니다 )
	// name = malloc(sizeof(char *ret_code));
		puts("Array read successfully, contents: ");  // 이는 코드 복붙으로 붙은 코드인데 정확히는 위에 ret_code 때 사용합니다, 역시 지우셔도 됩니다
		printf("%s\n", get);    // 정확히 나오는 것을 확인했습니다
		// for(int n = 0; n < size; n++) printf("%c ", get[n]); // 이는 size의 값을 아니까 적어서 돌리려고 했던건데 에러는 없었습니다만 출력물이 ???로 나옵니다  물론 영어는 정상적으로 나옵니다... 이 부분은 좀더 ... 알아봐야할꺼 같습니다
		// putchar('\n');        // 이 밑으로는 크게 의미 없습니다.
	// } else { // error handling
	//    if (feof(fp))
	// 	  printf("Error reading test.bin: unexpected end of file\n");
	//    else if (ferror(fp)) {
	// 	   perror("Error reading test.bin");
	//    }
	// }
 
fclose(fp);
}
 
마지막으로 이것저것 시도하다 보니 코드가 지저분 할수 있습니다
양해부탁드리며, 해결할 수 있는 문제 질문 드려 죄송합니다.

kombo67의 이미지

우선, 두서없는 글 죄송합니다

다시 마음 잡고 천천히 살펴보고 문제 해결했습니다
코드 올립니다 ( 테스트 코드이며, 본글의 실제 코드에서는 이 글 작성 후 수정할 예정입니다 )

    while(1) {
           fp = fopen("save_data_file", "wb");
           if (fp == NULL ) {
 
                perror("Cannot Save a data on File\n");
                exit(0);
            }
            printf("%lu\n", sizeof(description)); // 여기서 description 은 char[] 입니다
            fwrite(description, 1, sizeof(description), fp);
            printf("%d", sizeof(description)); // 해본 결과 174 ( 사이즈 확인하고 )
            fclose(fp);
 
 
            exit(0);
   }
}
 
입력 파일입니다
int main() {
 
	// assign variable
	FILE *fp;
	char *get;
	int size;
	fp = fopen("save_data_file", "rb");
	if(fp == NULL) {
		perror("Cannot Load a file : \n");
		exit(0);
	} else {
		printf("Sueccss\n");
	}
	fseek(fp, 0, SEEK_END);    // 파일 포인터를 파일의 끝으로 이동시킴
	size = ftell(fp);          // 파일 포인터의 현재 위치를 얻음
	rewind(fp);        // 코드 복붙 한거라 확인해야합니다만, 다시 처음으로 돌리는 함수인듯 합니다
	printf("%d\n", size);   // 174 확인하고
	get = (char *)malloc(sizeof(char)*size);     // 메모리 할당 했습니다
	fread(get, 1, size, fp); // rweads an array of doubles   // 1바이트를 174만큼 해서 변수에 넣습니다 여기서 get 변수는 char * 형 이기떄문에
                                                                                               // void * 에 위반되지 않습니다
	// printf("%zu", ret_code);    // 이는 확인 코드인데 여기선 사용하지 않습니다 ( 지우셔도 됩니다 )
	// name = malloc(sizeof(char *ret_code));
		puts("Array read successfully, contents: ");  // 이는 코드 복붙으로 붙은 코드인데 정확히는 위에 ret_code 때 사용합니다, 역시 지우셔도 됩니다
		printf("%s\n", get);    // 정확히 나오는 것을 확인했습니다
		// for(int n = 0; n < size; n++) printf("%c ", get[n]); // 이는 size의 값을 아니까 적어서 돌리려고 했던건데 에러는 없었습니다만 출력물이 ???로 나옵니다  물론 영어는 정상적으로 나옵니다... 이 부분은 좀더 ... 알아봐야할꺼 같습니다
		// putchar('\n');        // 이 밑으로는 크게 의미 없습니다.
	// } else { // error handling
	//    if (feof(fp))
	// 	  printf("Error reading test.bin: unexpected end of file\n");
	//    else if (ferror(fp)) {
	// 	   perror("Error reading test.bin");
	//    }
	// }
 
fclose(fp);
}
 
마지막으로 이것저것 시도하다 보니 코드가 지저분 할수 있습니다
양해부탁드리며, 해결할 수 있는 문제 질문 드려 죄송합니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.