0

How does fprintf work?

If I write fprintf(outfile, "test %d %d 255/r", 255, 255);

What does it mean? I know that outfile is the name my of output file. What would the other values mean?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Zeeshan Rang
  • 19,375
  • 28
  • 72
  • 100
  • 5
    You should also question your knowledge of the first parameter. "outfile" in **not** the *name* of your output file. – innaM Sep 03 '09 at 19:20
  • 6
    It's kinda sad, the first result of a "fprintf" google search would have told you everything about it. – DaClown Sep 03 '09 at 19:26
  • 8
    True, but now *this* discussion has a chance to show up in Google for the next person. Take that frown and turn it upside down. – Zack The Human Sep 03 '09 at 19:28

5 Answers5

6

"test %d %d 255/r" tells that after it will be arguments (and they are there: 255, 255) and they are expected to be of integer type. And they will be placed instead of %d.

In result you'll get string test 255 255 255 in your file.

For more infrormation read std::fprintf reference.

Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
3

The first parameter is a file handle, the second is a formatting string, and after that there is a variable number of arguments depending on how many format specifiers you used in your 2nd parameter.

Check the documentation, it contains all of the information you are asking.

Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
3

it's a formatted output to a file stream. It works like printf does, the difference is that printf always outputs to stdout.If you wrote

fprintf(stdout, "test %d %d 255\n", 255, 255);

it would be the same as the printf equivalent.

The second argument to it is the format string. The format string contains format specifiers, like %s, %d, %x. Yours contains two %ds. Each format specifier must have a corresponding argument in fprintf. Yours has two %d specifiers, so there are two numerical arguments:

fprintf(outfile, "Here are two numbers: %d, %d", 4, 5);

likewise, you could use string specifiers (%s), hexadecimal specifiers (%x) or long/long long int specifiers (%ld, %lld). Here is a list of them: http://www.cppreference.com/wiki/c/io/printf. Note that they are the same for all of the C formatted i/o functions (like sprintf and scanf).

Also, in your original example, "/r" will just literally print "/r". It looks like you were trying to do a carriage return ("\r").

Carson Myers
  • 37,678
  • 39
  • 126
  • 176
1

It's similar to printf, it just prints the output to a file.

Aziz
  • 20,065
  • 8
  • 63
  • 69
1

The second argument is the format string. Any additional arguments are the parameters to the specifier in the format string (in this case, %d). Check out http://www.cppreference.com/wiki/c/io/printf for a good intro to printf-style functions.

John Ledbetter
  • 13,557
  • 1
  • 61
  • 80