user7941771
user7941771

Reputation: 13

How to read Texts/Numbers from a File in C

I have this code to write a file named Phone Bill.txt

#include<stdio.h>
int main(){
    FILE *file;
    file=fopen("Phone Bill.txt","w");

    if(file!=NULL){
        fprintf(file, "Number\t\tLocal Call Chargers\tInternational Call Charges\tRoaming Charges\n");
    }

    double phoneNumber; 
    float localCharges, internationalCharges, roamingCharges;
    char wantToContinue='Y';

    while(wantToContinue=='Y'){
        printf("Enter Phone Number: ");
        scanf("%lf",&phoneNumber);
        printf("Enter Local Call Charges: ");
        scanf("%f",&localCharges);
        printf("Enter International Call Charges: ");
        scanf("%f",&internationalCharges);
        printf("Enter Roaming Call Charges: ");
        scanf("%f",&roamingCharges);

        if (file!=NULL)
        fprintf(file, "%.0lf\t%.0f\t\t\t%.0f\t\t\t\t%.0f\n",phoneNumber,localCharges,internationalCharges,roamingCharges);

        printf("\n");
        printf("Want to Continue Writing? (Y/N)");  
        scanf(" %c",&wantToContinue);
        if(wantToContinue=='Y'){
                wantToContinue='Y';
        }else if(wantToContinue=='N'){
                wantToContinue='N';
                fclose(file);
        }
        printf("\n");
    }



return 0;
}

Here's the screenshot of the Phone Bill.txt after Writing the contents to the file:

Phone Bill Screenshot

This is the code I used to read the content (numbers) from the Phone Bill.txt file:

#include<stdio.h>
int main(){
    FILE *file;

    char strings[200];
    double phoneNumber; 
    float localCharges, internationalCharges, roamingCharges;

    file=fopen("Phone Bill.txt","r");

    if(file!=NULL){
        fscanf(file,"%.0lf\t%.0f\t\t\t%.0f\t\t\t\t%.0f\n",phoneNumber,localCharges,internationalCharges,roamingCharges);
        printf("%.0lf %0.f %0.f %0.f",phoneNumber,localCharges,internationalCharges,roamingCharges);
    }
return 0;
}

But my Output is:

0 0 0 0

Can you please tell me why am I getting this error???*

Thank you!

Upvotes: 0

Views: 72

Answers (3)

user3629249
user3629249

Reputation: 16540

in general, should always make code as simple as possible (and no simpler)

The following proposed code:

  1. compiles cleanly
  2. performs the desired functionality

Note: since the file is already formatted, only need to echo the lines to the terminal.

#include <stdio.h>  // fgets(), fopen(), fclose(), puts(), perror()
#include <stdlib.h> // exit(), EXIT_FAILURE

int main( void )
{
    char strings[200];

    FILE *fp = fopen("Phone Bill.txt","r");
    if( !fp )
    {
        perror( "fopen to read Phone Bill.txt failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    // read, print each line:
    while( fgets( strings, sizeof( strings ), fp ) )
    {
        puts( strings );
    }

    if( !feof( fp ) )
    { // then read error
        perror( "read of Phone Bill.txt failed" );
        fclose( fp );
        exit( EXIT_FAILURE );
    }

    fclose( fp );
    return 0;
} // end function: main

regarding the OPs posted code to read the file:

a \t is 'white space', so should not be in the fscanf() format string

The first line of the file is not part of the data, so needs to be read in separately, Suggest using fgets() to read into strings[] then can immediately echo with puts()

the second line through the end of the file can be easily read with:

while( 4 == fscanf( file, " %lf %f %f %f", &phoneNumber, &localCharges, &internationalCharges, &roamingCharges ) ) 
{
    ....
}

the format string for the fscanf() can be reduced further (because %f and %lf input/format specifications discard leading 'white space' to:

"%lf%f%f%f"

Upvotes: 0

Weather Vane
Weather Vane

Reputation: 34585

Firstly, you are trying to scan the first line of the file which is headings.

Secondly, you need to remove all the noise from the fscanf format definitions: those format types automatically ignore leading whitespace.

Thirdly, you need to pass addresses to fscanf. Here is a working edit.

#include <stdio.h>

int main(){
    FILE *file;
    char strings[200];
    double phoneNumber; 
    float localCharges, internationalCharges, roamingCharges;
    file=fopen("Phone Bill.txt","r");
    if(file!=NULL){
        fgets(strings, sizeof strings, file);       // read the headings
        fscanf(file,"%lf%f%f%f", &phoneNumber, &localCharges, &internationalCharges, &roamingCharges);
        printf("%.0lf %0.f %0.f %0.f", phoneNumber, localCharges, internationalCharges, roamingCharges);
        fclose(file);                               // don't forget to close
    }
    return 0;
}

Additionally, you must check the return value from fscanf which should be 4 the number of items scanned.

Lastly, I suggest that phoneNumber should not be double or even unsigned long long, but something like char phoneNumber[MAXPHLEN]. Phone numbers can begin with a 0 or 00 which will otherwise be lost. More generally, that will also accommodate the + used in IDD and the alphabetic equivalents of numbers which were, and perhaps still are, used on some phone dials.

EDIT from the OP's comment about using a string for a phone number. I restrict the string input length to prevent overflow, and also check the number of items scanned - in a loop to read all the data.

#include <stdio.h>

#define MAXPHLEN 50

int main(){
    FILE *file;
    char strings[200];
    char phoneNumber[MAXPHLEN];
    float localCharges, internationalCharges, roamingCharges;
    file=fopen("Phone Bill.txt","r");
    if(file!=NULL){
        fgets(strings, sizeof strings, file);       // read the headings
        while((fscanf(file,"%49s%f%f%f", phoneNumber, &localCharges, &internationalCharges, &roamingCharges)) == 4) {
            printf("%s %0.f %0.f %0.f\n", phoneNumber, localCharges, internationalCharges, roamingCharges);
        }
        fclose(file);                               // don't forget to close
    }
    return 0;
}

Upvotes: 1

Mostafa Abdulrazic
Mostafa Abdulrazic

Reputation: 309

Change your fscanf to point to the variables:

So:

fscanf(file,"%.0lf\t%.0f\t\t\t%.0f\t\t\t\t%.0f\n",&phoneNumber,&localCharges,&internationalCharges,&roamingCharges)

Upvotes: 0

Related Questions