c - 使用C获取文本文件中两个特定点之间的特定信息

标签 c text-files

所以我有这个文本文件,其中包含某个电子邮件地址的人喜欢的内容:

email1@gmail.com
Likes:
Animals
Sports

email2@gmail.com
Likes:
Science
Animals

我真正需要的是某些用户电子邮件喜欢的那些特定单词(scanf 选择的时间只有一封电子邮件)和他的每个喜欢的主题(所有这些都只是一个单词)将被用于一个我的代码的功能(例如:功能(动物))。

编辑:我只想要我选择的电子邮件中的每个单词都喜欢(案例 email1 我想要从文本文件中提取单词“动物”和“运动”,因为我需要使用这些单词)。我怎样才能用 C 做到这一点?

最佳答案

试试下面的代码

#include<stdio.h>
#include<string.h>

int main()
{
    FILE * fptr = NULL;
    fptr = fopen("File.txt" , "r");//Let File.txt be the required file
    if(fptr==NULL)//Check if file was opened successfully
    {
        printf("File could not be opened");
        return 0;
    }
    printf("File opened\n");
    char buff[1024];//To store line read from file
    char email[1024];//To store email id
    printf("Enter email id:");
    scanf("%s",email);
    int found=0;
    while(fscanf(fptr,"%[^\n]\n",buff))//Read file line by line and store the line to buff
    {
        //printf(":%s:",buff);

        if(strstr(buff,"@")!=NULL)//Set found=0 if the line in the file is an email id. Here I am checking for the word "@" in the line read since an email id will surely have an @ symbol. Replace it with some checking function to verify if it's an email id
        {
            if(found==1)//If the email was already found break out of the loop
                break;
            found=0;
        }
        if(found==1)//If found=1 buff will have your required Likes including the word Likes:
        {
            if(strcmp("Likes:",buff)!=0)//If required word is not 'Likes:' since only the likes is required not the word 'Likes:'
            {
                printf("%s\n",buff);//buff contains the required like. It can be used as your functions argument.
            }
        }

        if(strcasecmp(email,buff)==0)//Set found=1 if the required email is found 
            found=1;    
        if(feof(fptr))//Break out of the loop if file end is reached
            break;
    }
}

如果 email1 是必需的电子邮件 ID,那么您的输入应该是 email1@gmail.com,因为它以这种格式存储在文件中。

关于c - 使用C获取文本文件中两个特定点之间的特定信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50299140/

相关文章:

C/程序集 : how to change a single bit in a CPU register?

c++ - 关闭游标错误mysql连接器c++ 8.0

c - C 中的逆波兰计算器 : using argv as a way to store and retrieve results

bash - 通过连接的第一列连接 3 个文件(是 awk)?

c++ - 如何在 C++ 中使用 ifstream 从文本文件读取逗号?

c - C 中的字符串行为

javascript - HTML5 与 javascript 解析和显示文本文件

.net - 磁盘空间 StreamWriter 与 Out-File

python - 从文本文件读取数据并使用 1-liner 填充列表

c - 将数据文件读入二维数组后出现段错误