[英]How do I print the current line?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i, f=0;
int c;
char file_name[100];
char search[10];
printf("Enter the file name:");
scanf("%s", file_name);
printf("Search word:");
scanf("%s", search);
FILE *f = fopen((strcat(file_name, ".txt")), "rb");
fseek(f, 0, SEEK_END);
long pos = ftell(f);
fseek(f, 0, SEEK_SET);
char *bytes = malloc(pos);
fread(bytes, pos, 1, f);
fclose(f);
/*search*/
if (strstr(bytes, search) != NULL){
printf("found\n");
f = 1;}
else{
printf("Not found\n");
f=0;}
if (f==1){ /* if found...print the whole line */
....}
free(bytes);
}
上面说的是我从.txt文件中搜索字符串的程序。 找到后,将打印“找到”,否则将打印“未找到”。 现在,我想打印出该字符串是其中一部分的完整行。 我当时正在考虑使用“ f == 1”作为“如果找到”的条件来打印整行,而不是真的确定最佳的处理方法。
首先,您需要修正读取操作,以保留从NUL终止文件中读取的数据:
char *bytes = malloc(pos + 1);
fread(bytes, pos, 1, f);
bytes[ pos ] = '\0';
也添加一些错误检查-检查malloc()
和fread()
。 这是一个好习惯。
然后,如果找到您的字符串,请拆分当时读取的内容:
char *found = strstr( bytes, search );
if ( found != NULL )
{
*found = '\0';
char *lineStart = strrchr( bytes, '\n' );
char *lineEnd = strchr( found + 1, '\n' );
.
.
我将由您自己决定这两个中的一个或两个均为NULL的含义。
同样,使用fseek()找出文件中有多少字节在技术上是错误的,因为ftell()不会返回字节偏移量,而只会返回fseek()可以使用的值以返回文件中的同一位置。文件。 在某些体系结构中,ftell()返回无意义的数字。
如果您想知道文件的大小,请在打开的文件上使用stat()
或fstat()
:
struct stat sb;
FILE *f = fopen(...)
fstat( fileno( f ), &sb );
off_t bytesInFile = sb.st_size;
另请注意,我没有使用多long
-我使用过off_t
。 当32位程序的文件大小超过2 GB时,使用long
在文件中存储字节数会导致严重的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.