programing

포인터를 파일 시작으로 재설정

css3 2023. 10. 27. 22:07

포인터를 파일 시작으로 재설정

명령줄 입력 또는 파일의 시작으로 포인터를 재설정하려면 어떻게 해야 합니까?예를 들어, 내 기능은 파일에서 한 줄로 읽고 getchar()를 사용하여 출력하는 것입니다.

    while((c=getchar())!=EOF)
    {
        key[i++]=c;
        if(c == '\n' )
        {
            key[i-1] = '\0'
            printf("%s",key);
        }       
    }

이를 실행한 후 포인터가 EOF를 가리키고 있다고 가정합니까?파일의 시작 부분을 다시 가리키거나 입력 파일을 다시 읽으려면 어떻게 해야 합니까?

./function < 입력으로 입력합니다.txt)

만약 당신이.FILE*이외에stdin, 다음을 사용할 수 있습니다.

rewind(fptr);

아니면

fseek(fptr, 0, SEEK_SET);

포인터를 파일의 시작 부분으로 재설정합니다.

당신은 그것을 위해 할 수 없습니다.stdin.

포인터를 재설정할 수 있어야 할 경우 파일을 인수로 프로그램에 전달하고 다음을 사용합니다.fopen파일을 열고 내용을 읽습니다.

int main(int argc, char** argv)
{
   int c;
   FILE* fptr;

   if ( argc < 2 )
   {
      fprintf(stderr, "Usage: program filename\n");
      return EXIT_FAILURE;
   }

   fptr = fopen(argv[1], "r");
   if ( fptr == NULL )
   {
      fprintf(stderr, "Unable to open file %s\n", argv[1]);
      return EXIT_FAILURE;
   }

    while((c=fgetc(fptr))!=EOF)
    {
       // Process the input
       // ....
    }

    // Move the file pointer to the start.
    fseek(fptr, 0, SEEK_SET);

    // Read the contents of the file again.
    // ...

    fclose(fptr);

    return EXIT_SUCCESS;
}

파이프 연결/방향 전환된 입력은 그렇게 작동하지 않습니다.옵션은 다음과 같습니다.

  • 입력 내용을 내부 버퍼(이미 실행 중인 것처럼 보임)로 읽거나,
  • 대신 파일 이름을 명령줄 인수로 전달하고 원하는 대로 수행합니다.

언급URL : https://stackoverflow.com/questions/32366665/resetting-pointer-to-the-start-of-file