在 C 中读取文件
Read files in C
谁能告诉我,我们如何使用 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);
}
显然,输入不能作为字符串读取...
谁能告诉我,我们如何使用 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);
}
显然,输入不能作为字符串读取...