2011-10-18 6 views
2

안녕하세요.이 모든 것은 기본적으로 이전 질문에 대한 확장입니다. 내가 그것을 잘 작동다른 값을 읽고 쓰는 것

short int x= 254; 
FILE * f1 = fopen("infile" ,"w"); 
fwrite (&x , 1 , sizeof(short int) , f1); 

사용하여 파일의 짧은 int 값을 적게하지만 난이

short int y ; 
fread(&y , 2, 1 ,f1); 
printf("%d" , y); 

같은 값을 검색하려고 할 때 그것은 나를 등등 8180 및 다음 시간 12276 대답했다 ... 다시 FR을 읽고 싶다면 내가

실제로 내 파일에 짧은 정수를 저장하고 그들에게 내가하고있는 일 시까 하나를 검색 할해야 할 일이 잘못 친절하게 나에게

답변

0

안내 당신이 방금 쓴 파일이 있다면, "w +"옵션을 사용하여 읽고 쓸 수 있어야합니다. 그런 다음 다시 파일의 시작 부분으로 추구해야합니다 원래 코드는 확인되지 않았 음을

// Open the file 
const char* fname = "infile"; 
FILE * f1 = fopen("infile" ,"wb"); 
if(f1 != NULL) 
{ 
    printf("opened file '%s' for writing\n", fname); 

    // Write two bytes 
    short int x = 254; 
    size_t bytes_written = fwrite(&x, 1, sizeof(short int), f1); 
    printf("%hd bytes written\n" , bytes_written); 

    // We're done with the file so close it 
    fclose(f1); 
} 
else 
{ 
    // Something went wrong and we failed to open the file 
    printf("failed to open file '%s' for writing\n", fname); 
} 

// re-open the file 
FILE * f2 = fopen("infile" ,"rb"); 
if(f2 != NULL) 
{ 
    printf("opened file '%s' for reading\n", fname); 

    // Read the two bytes back in 
    short int y = -9999; 
    size_t bytes_read = fread(&y, 1, sizeof(short int), f2); 
    printf("%hd bytes read: %hd\n", bytes_read, y); 

    // We're done with the file so close it 
    fclose(f2); 
} 
else 
{ 
    // Something went wrong and we failed to open the file 
    printf("failed to open file '%s' for reading\n", fname); 
} 

참고 : 또는

// Open the file 
const char* fname = "infile"; 
FILE * f1 = fopen("infile" ,"wb+"); 
if(f1 != NULL) 
{ 
    printf("opened file '%s' for writing/reading\n", fname); 

    // Write two bytes 
    short int x = 254; 
    size_t bytes_written = fwrite(&x, 1, sizeof(short int), f1); 
    printf("%hd bytes written\n" , bytes_written); 

    // Seek to the start of the file 
    int seek_result = fseek(f1, 0, 0); 
    if(seek_result == 0) 
    { 
     printf("found beginning of file\n"); 
    } 
    else 
    { 
     printf("failed to seek to beginning of file\n"); 
    } 

    // Read the two bytes back in 
    short int y = -9999; 
    size_t bytes_read = fread(&y, 1, sizeof(short int), f1); 
    printf("%hd bytes read: %hd\n", bytes_read, y); 

    // We're done with the file so close it 
    fclose(f1); 
} 
else 
{ 
    // Something went wrong and we failed to open the file 
    printf("failed to open file '%s' for writing/reading\n", fname); 
} 

, 별도의 작업으로 읽기/쓰기 수 fread의 값을 반환하여 파일에서 실제로 내용을 읽을 지 여부를 확인합니다. 만약 당신이 그것을했다면 0 바이트를 읽었다는 것을 나타내는 0을 반환하는 것을 보았을 것입니다. 파일에서 아무 것도 읽지 않고 y을 초기화하지 않으면 난수 일 가능성이 높습니다.

+0

덕분에 선생님 – mainajaved

1

대부분의 경우 쓰기와 읽기 사이에서 파일을 닫았다가 다시 열지 않습니다. 첫 번째 글쓰기, 닫고 플러시하기, 그리고 독서하기 등 두 가지 작업을 수행하는 작은 함수를 만드는 것이 좋습니다. 어떤 종류의 결과를 얻었는지보십시오. 또한 바이너리 모드를 사용하고 있는지 확인하십시오.

+0

확인 선생님 덕분하지만 선생님 작정는 밖으로 작업 중 존의 대답 또는 사용하여 시작 추구하여 파일을 다시 열기/닫기하여이 작업을 수행 이진 모드 :/ – mainajaved

+0

이번에는했지만 jmoreno는 정확합니다. 경우에 따라 텍스트 판독기로 2 진 데이터를 쓰는 (더 중요하게는) 경우 텍스트 모드에서 읽기/쓰기가 실패하는 경우가 있습니다. –

+1

@mainajaved : '바이너리 모드를 사용해야 할 수도 있습니다.'라고 말해야했는데 초기 성공에도 불구하고 여전히 작성해야하는 경우가 있습니다. 어쨌든 이제 다행입니다. – jmoreno

0

나는 존 케이지 응답 (나를 그를하지 upvote에!)에 동의 또한

주의

그 (오래 전에), 바이너리 파일을 필요로 윈도우/DOS 시스템 'WB', 'RB'로 열 수 'w'와 'r'대신에. 나는 그것이 아직도 사실이지만, 아무런 문제도 없다고 확신하지 않는다.

short int x= 254; 
int nwritten; 
FILE * f1 = fopen("infile" ,"w+b"); 
nwritten=fwrite (&x , 1 , sizeof(short int) , f1); /* check number of shorts written */ 
if (nwritten != 1) fprintf(stderr,"Error: %d short written\n",nwritten); 

을 그리고 독서 부분 : 여기

코드의 비트가 일을 더 명확 얻을 수있어 또한

short int y ; 
int nread; 
nread=fread(&y , sizeof(short int), 1 ,f1); /* check number of shorts read */ 
if (nread == 1) printf("%d" , y); 
else fprintf(stderr,"Error: could not read 1 short int (%d read)\n",nread); 

이 파일 내부의 위치는 각 읽기 후에 증가 기억/쓰다. 읽기 전에 파일의 시작 부분으로 돌아가고 싶을 수도 있습니다.

fseek(f1,0L,SEEK_SET); /* you also can use rewind(f1); for the same result */ 

전체 코드 :

short int x= 254; 
int nwritten; 
FILE * f1 = fopen("infile" ,"w+b"); 
nwritten=fwrite (&x , 1 , sizeof(short int) , f1); /* check number of shorts written */ 
if (nwritten != 1) fprintf(stderr,"Error: %d short written\n",nwritten); 

short int y ; 
int nread; 
fseek(f1,0L,SEEK_SET); /* get back to the start */ 
nread=fread(&y , sizeof(short int), 1 ,f1); /* check number of shorts read */ 
if (nread == 1) printf("%d" , y); 
else fprintf(stderr,"Error: could not read 1 short int (%d read)\n",nread); 
+0

감사합니다. alot sir – mainajaved

관련 문제