Using fseek with stdout

Can fseek be used when the arg file pointer is stdout?

I tried this in a script where I was trying to overwrite the last "," in a comma separated list with ")"

eg.

fprintf(stdout, "1,2,3,4,");

fseek(stdout, -1, SEEK_CUR);

fprintf(stdout, ")");

      

for achievement:

1,2,3,4)

Unlike

1,2,3,4)

Unfortunately, I was outputting the last

+4


source to share


2 answers


You can successfully use fseek

in stdout

if and only if the stdout

stream is referenced for searching.

If your program's standard output goes to a terminal or something similar (usually the default) or a pipe, it fseek

will fail. If it goes to a file because you ran a program with redirected output, then it fseek

may work the same as for any other file.

Each time you call fseek

, you must check its return value to see if it succeeds or fails.

It stdout

is probably bad practice to assume what can be found because it is a very bad guess.



Your goal is to print a sequence of elements with ", "

between elements, but not before the first or after the last. Neither fseek

printing nor printing '\b'

is a good approach to what you are trying to do. Instead of printing the final comma and then trying to erase it, you should only print the comma if you haven't just printed the last item in the list. Finding this out can be nontrivial.

But a simpler approach is to put a comma before each element, unless it's the first. You cannot always tell if you are printing the last value of the sequence. You can always tell if you are typing first.

Pseudo-code:

bool is_first_item = true
for each item
    if is_first_item
        is_first_item = false
    else
        print ", "
    end if
    print item
end for 

      

+6


source


Using fseek

on is stdout

not possible. Instead, you can use the backspace character '\b'

to move the cursor back one space:

fprintf(stdout, "1,2,3,4,");

fprintf(stdout, "\b)");

      



Note: this will only work if it stdout

points to a terminal and does not redirect to a file or pipe. Also, if the cursor is at the beginning of a line, this is not guaranteed. In general, there are only a few cases where this will work.

+3


source







All Articles