Im trying to open a file, and then read a user defined number of characters from said file. I want to do this using scanf but I can't quite figure out how it works. I can get scanf to work just fine but I can't determine how to specify the maximum number of characters to read.

8 Years
Discussion Span
Last Post by dansnyderECE

There is a function called getline(), I'm not familiar with just get(). But you can use the >> operator with ifstream. Take a look and let us know when you run into a particular question.



> I can't determine how to specify the maximum number of characters to read.
scanf() does not offer a user-defined field width like printf(). The way to make it dynamic is with sprintf.

char fmt[15];
char *data = malloc(n);

sprintf(fmt, "%%dc", n);
scanf(fmt, data);

Why not just use a loop and getc()? Better yet, why not use the C++ string class and iostreams instead? They are much more user friendly.

Edited by Radical Edward: n/a


This worked well for me:

ifstream is;
            is.open ("test.txt", ios::binary );
            is.read (buffer,length);
            delete[] buffer;
            if(is.fail())//if an error was encounter before eof...
                top->v0_in = -1;//flag v0_in as negative
            else if (is.eof())
                top->v0_in = 0;//if eof is reached set v0_in to zero
                top->v0_in = is.gcount();//counts the number of characters read before closing

Edited by dansnyderECE: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.