How to read a text file upto certain position in C

2019-08-17 12:59发布

I am passing a string as an argument to my program and extracting its position in a text file. Can we read a text file only upto this certain position in C?? If yes, then please tell me how.

标签: c file text io
2条回答
男人必须洒脱
2楼-- · 2019-08-17 13:23

What you need is the strstr function written for file handles. This is a generic implementation of strstr. You can pretty easily modify it to use file buffers instead of another string, so I won't do your work for you :P

char *
strstr(const char *haystack, const char *needle)
{
        char c, sc;
        size_t len;

        if ((c = *needle++) != '\0') {
                len = strlen(needle);
                do {
                        do {
                                if ((sc = *haystack++) == '\0')
                                        return (NULL);
                        } while (sc != c);
                } while (strncmp(haystack, needle, len) != 0);
                haystack--;
    }
        return ((char *)haystack);
}
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-08-17 13:48

Just use fread() up to the number of bytes that puts you to that "position" in the file. For example, if you know you want to read up to the position at 1928 bytes, just read that many bytes in with fread.

查看更多
登录 后发表回答