how can I output a certain text from a file in c?

Viewed 75

Good evening!

I need to output the first, third, fifth, and so on to the fifteenth real numbers to the console from the file. So far, I have only output all the lines from the file.

How can I output a certain text from a file?

Below are the commands executed on my terminal and their results:

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

Code:

#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

Output:

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
2 Answers

Since I neither have your file nor your expected output, I had to make assumptions about the unclear parts.

The program below should help.

//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

Once you've gotten past the lines you want to skip entirely (which you haven't specified how to identify), this will print the every other line:

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