Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用C语言读取文件_C_Fseek - Fatal编程技术网

用C语言读取文件

用C语言读取文件,c,fseek,C,Fseek,有谁能告诉我,我们如何使用c来读取文件的特定部分 我有一个1000个字符的文件,我想读它的部分,例如:第一个0到100个字符,然后101到200个字符,依此类推。我试过fread()和fseek(),但都做不到 我想要一个指针,从文件的开头开始,读取100个字符,然后移动到101位置,然后再次读取100个字符,以此类推。希望这有帮助 #include <stdio.h> #include <stdlib.h> #include <unistd.h> #incl

有谁能告诉我,我们如何使用c来读取文件的特定部分

我有一个1000个字符的文件,我想读它的部分,例如:第一个0到100个字符,然后101到200个字符,依此类推。我试过fread()和fseek(),但都做不到

我想要一个指针,从文件的开头开始,读取100个字符,然后移动到101位置,然后再次读取100个字符,以此类推。

希望这有帮助

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(void)
{
    int fd;
    char line[101] = {0};
    ssize_t readVal;
    int ret;

    /* open the file in question */
    fd = open("tmpp", O_RDONLY);
    if ( fd < 0 )
        exit(EXIT_FAILURE);

    /* read the first 100bytes (0-99)*/
    readVal = read(fd, line, 100); 
    printf("Retrieved first %zu bytes:\n %s\n\n", readVal, line);

    /* read the next 100bytes (100-199)*/
    readVal = read(fd, line, 100); 
    printf("Retrieved second %zu bytes:\n %s\n\n", readVal, line);

    /* jump to location 300, i.e. skip over 100 bytes */
    ret = lseek(fd, 300, SEEK_SET);
    if ( ret < 0 ) {
        close( fd );
        return -1;
    }

    /* read next 100bytes (300-399) */
    readVal = read(fd, line, 100); 
    printf("Retrieved third %zu bytes - at location 300:\n %s\n\n", readVal, line);

    /* close the file descriptor */
    close(fd);
    exit(EXIT_SUCCESS);
}
#包括
#包括
#包括
#包括
#包括
#包括
内部主(空)
{
int-fd;
字符行[101]={0};
ssize_t readVal;
int ret;
/*打开有问题的文件*/
fd=打开(“tmpp”,仅限Ordu);
如果(fd<0)
退出(退出失败);
/*读取前100字节(0-99)*/
readVal=读取(fd,第100行);
printf(“检索到的第一个%zu字节:\n%s\n\n”,readVal,第行);
/*读取下一个100字节(100-199)*/
readVal=读取(fd,第100行);
printf(“检索到的第二个%zu字节:\n%s\n\n”,readVal,第行);
/*跳转到位置300,即跳过100个字节*/
ret=lseek(fd,300,寻道集);
如果(ret<0){
关闭(fd);
返回-1;
}
/*读取下一个100字节(300-399)*/
readVal=读取(fd,第100行);
printf(“检索到的第三个%zu字节-位于位置300:\n%s\n\n”,readVal,第行);
/*关闭文件描述符*/
关闭(fd);
退出(退出成功);
}

显然,输入不能作为字符串读取…

显示您的代码。当您使用
fread
读取前100个字节时,文件指针将放置在字节101上,因此下一次调用
fread
将从该位置开始读取。它会自动发生,就像你想要的那样。如果您创建并向我们展示,我们将能够更好地帮助您。也请。和(基本上)