Srijan
Srijan

Reputation: 1274

Unable to read from a file

I have written a code that reads from a file named network.dat

The code I wrote is

    f = fopen("network.dat", "r");
    if(f == NULL)
        exit(1);
    int read, N;

    printf("%p\n", f);//output file pointer, included this just to check if file is opened properly
    fscanf(f, "%d%d", &N, &read);//error here
    cout<<N; 

The file is being opened correctly and am getting the file pointer (49897488) as output but the line following it is where program stops working and I don't get N as output. Please tell if other detail is required. Contents of network.dat are

10 1
1   6   1.28646
1   7   1.2585
2   9   1.33856

and so on. Am just focusing on first 2 numbers from the file i.e. 10 and 1.

Upvotes: 0

Views: 290

Answers (4)

Alec Danyshchuk
Alec Danyshchuk

Reputation: 307

This seems to work Srijan. The code is a quick and dirty cut and paste job, zero points for style, but it does the job as a test. It seems that the number of fields in the records needs to match the fields in the print format string. I added a 3rd field in your test data on record 1 of 1.9999 and it worked. I doubt this is a technically pure explanation.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <cstring>
#include <cstdlib>
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
using std::ios;

int main(int argc, char *argv[])
{
//int read;
//int N;
int res;
FILE *f;


f = fopen("network.dat", "r");
    if(f == NULL)
        exit(1);
    int read, N;
    float f3;

    printf("%p\n", f);//output file pointer, included this just to check if file is opened properly
    for (;;)
        {
    res = fscanf(f, "%d%d%f", &N, &read, &f3);//error here
    if (res <= 0)
        {
        printf("err %d\n",errno);
        break;
        }
    cout<<N << " " << read << "\n";
        }
}

Upvotes: 1

obataku
obataku

Reputation: 29656

As I stated in my comment, the problem is that your format specifier is incorrect. Try

fscanf(f, "%d%d", &N, &read);

Since you're using cout I'm fathoming a guess that this is actually C++ code... honestly, you should really not be doing this the canonical C way. Instead, use ifstream.

std::ifstream input("network.dat");
int N, read;
input >> N >> read;
std::cout << N << ' ' << read << std::endl;

Upvotes: 0

teppic
teppic

Reputation: 8205

Your scanf() format string is incorrect. "%d,%d" looks for two integers separated by a comma. If you want to read two integers separated by whitespace, just do "%d%d".

Upvotes: 1

Isaac Betesh
Isaac Betesh

Reputation: 3000

You code expects all the characters in the file up until the first whitespace to be an int. If the file doesn't begin with an int, that could be the reason it's failing.

Upvotes: 0

Related Questions