Why can't I call read() twice on an open file?

后端 未结 7 1576
挽巷
挽巷 2020-11-21 05:05

For an exercise I\'m doing, I\'m trying to read the contents of a given file twice using the read() method. Strangely, when I call it the second time, it doesn\

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 05:41

    Every open file has an associated position.
    When you read() you read from that position. For example read(10) reads the first 10 bytes from a newly opened file, then another read(10) reads the next 10 bytes. read() without arguments reads all of the contents of the file, leaving the file position at the end of the file. Next time you call read() there is nothing to read.

    You can use seek to move the file position. Or probably better in your case would be to do one read() and keep the result for both searches.

提交回复
热议问题