Hi All

Can anyone tell me how to read a file but only print to the screen certain parts of it? Below is what I've got already - apologies if it's very basic, I'm new to this! All I can do is get a program which prints the whole file to the screen. What I need to do is create a program which can pick out numbers from the file which are higher than 0.7 and print only those to the screen. I have looked everywhere for examples of this but no joy.

Any advice would be appreciated.

Thanks

#include <stdio.h>
#include <stdlib.h>
#include <clib.h>

int main()
{
  printf("Please enter the name of the file you require: ");
    FILE *z;
    char x[1000];
    char fname[128];
    gets(fname);
    z=fopen(fname,"r");
    if (!z)
    return 1;
    while (fgets(x,1000,z)!=NULL)
    printf("%s",x);
    return (0);
}

Recommended Answers

All 3 Replies

1. never ever use gets() -- it can destroy your program at runtime if you enter more characters than the input buffer can hold. Use fgets() instead to limit input. The downside to that function is you have to remove the trailing '\n' charcter (the <Enter> key)

2. I assume the file contains floats and no other non-float characters. If that's the case then use fscanf() to read the floats then simply compare the value read to 0.7F.

float num;
while (fscanf(z,"%f",&num) > 0)
{
    if( num >= 0.7F)
       printf( <code here> );
}

so where u able to figure out ur code?
i am a new programmer in C, i know a lot of JAVA but this C is just so much....BLAH!

commented: Asking this question of a 3 year old thread is the ultimate insult to this forum! Get with it! -3

That pretty much sums up my opinion of Java too :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.