任何人都可以告诉我,我们如何使用c。
读取文件的特定部分我有一个1000个字符的文件,我想读它的部分例如:首先是0到100个字符,然后是101到200,依此类推。我试过fread()和fseek()但是做不到。
我想要一个类似指针的东西从文件的开头开始并读取100个字符,然后移动到101位置,然后再次读取100个字符,依此类推。
答案 0 :(得分:-1)
希望这会有所帮助......
#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);
}
显然,输入可以不是字符串......