【问题标题】:how can I output a certain text from a file in c?如何从 c 文件中输出特定文本?
【发布时间】:2021-10-10 10:38:08
【问题描述】:

晚上好!

我需要从文件中输出第一个、第三个、第五个到第十五个实数到控制台。到目前为止,我只输出了文件中的所有行。

如何从文件中输出特定文本?

以下是在我的终端上执行的命令及其结果:

:~/Документы/Cpp/projects$ vim test0.c
:~/Документы/Cpp/projects$ cat test0.c

代码:

#include<stdio.h>  
void main(void) 
{
    FILE *file;
    char str1[80];
    char *str2;

    file=fopen("dat.txt","r");

    for(int i=0;i<17;i++)  
    {
        str2=fgets(str1,sizeof(str1),file);
        printf("%s",str1);
    }

    fclose(file);
}
:~/Документы/Cpp/projects$ gcc -o test0 test0.c
:~/Документы/Cpp/projects$ ./test0

输出:

0x7ffc2b05b698
0  9  11  4  1  
7.5
5.8
7.2
4.2
4.5
7.3
1.7
1.5
8.0
0.6
3.9
7.0
3.0
2.8
7.2

【问题讨论】:

  • @Bart 这怎么行?它不会抑制每个偶数行的输出。
  • 为什么这个标签是task
  • 如果你从不使用str2,为什么要计算它?
  • @Bart 这也可以被视为一个选项。但是有这样的可能性使用数组来做到这一点吗?你有什么想法吗?
  • 您的main 函数不符合标准C,请参阅n1570。在实践中,使用gcc -Wall -Wextra -g -o test0 test0.c 编译您的代码,然后使用GDB 调试器。也可以使用valgrind。有时考虑生成一些 C 代码(例如使用 RefPerSys...)。通过电子邮件(俄语、法语或英语)联系我至basile@starynkevitch.net

标签: c file


【解决方案1】:

由于我既没有你的文件也没有你预期的输出,所以我不得不对不清楚的部分做出假设。

下面的程序应该会有所帮助。

//macros here
#define BUFFERSIZE 64
#define PATHLENGTH 255

//header files here
#include <stdio.h>
#include <stdlib.h>

//functions here
int main()
{
    FILE *in;
    //ask user for input
    {
        char path[PATHLENGTH];
        printf("Enter path of file:\n");
        fgets(path, PATHLENGTH, stdin);
        sscanf(path, "%s", path);//gets rid of trailing delimiter
        in = fopen(path, "r");
    }
    
    if(in == NULL)
    {
        printf("Unable to open file.\n");
        perror("Error.\n");
        return -1;
    }
    else
    {
        char input[BUFFERSIZE];
        float number;
        int i = 0;
        
        while(fgets(input, BUFFERSIZE, in) != NULL)
        {
            //assuming there is only one number per line
            if(sscanf(input, "%f", &number) == 1)//reads a number while preventing input mismatch
            {   ++i;
                if(i%2 != 0)//not even
                    printf("%f\n", number);
            }
        }
        fclose(in);
    }
    return 0;
}

dat.txt

7.5
5.8
7.2
4.2
4.5
7.3
1.7
1.5
8.0
0.6
3.9
7.0
3.0
2.8
7.2

【讨论】:

    【解决方案2】:

    一旦您跳过了要完全跳过的行(您尚未指定如何识别),这将打印每隔一行:

     if (i % 2 == 0)
        printf("%s",str1);
    

    【讨论】:

    • 为什么使用百分比?结果将导致偶数。而且这里还有我不需要输出的数据。例如:0x7ffc2b05b698 0 9 11 4 1
    • 这是模运算符。
    • 但是没有这个元素我怎么能输出呢? 0x7ffc2b05b698
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 1970-01-01
    相关资源
    最近更新 更多