C Programming

  Home  Computer Programming  C Programming


“C Programming Interview Questions and Answers will guide you that C is a general-purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories and C language is for use with the Unix operating system. If you are developer and need to update your software development knowledge regarding basic and advance C programming or need to prepare for a job interview? Check out this collection of basic and advance C programing Interview Questions and Answers.”



221 C Programming Questions And Answers

141⟩ How can I change their mode to binary?

I'm writing a ``filter'' for binary files, but stdin and stdout are preopened as text streams. How can I change their mode to binary?

There is no standard way to do this. On Unix-like systems, there is no text/binary distinction, so there is no need to change the mode. Some MS-DOS compilers supply a setmode call. Otherwise, you're on your own.

 153 views

142⟩ What is the difference between text and binary I/O?

In text mode, a file is assumed to consist of lines of printable characters (perhaps including tabs). The routines in the stdio library (getc, putc, and all the rest) translate between the underlying system's end-of-line representation and the single n used in C programs. C programs which simply read and write text therefore don't have to worry about the underlying system's newline conventions: when a C program writes a 'n', the stdio library writes the appropriate end-of-line indication, and when the stdio library detects an end-of-line while reading, it returns a single 'n' to the calling program.

In binary mode, on the other hand, bytes are read and written between the program and the file without any interpretation. (On MS-DOS systems, binary mode also turns off testing for control-Z as an in-band end-of-file character.)

Text mode translations also affect the apparent size of a file as it's read. Because the characters read from and written to a file in text mode do not necessarily match the characters stored in the file exactly, the size of the file on disk may not always match the number of characters which can be read from it. Furthermore, for analogous reasons, the fseek and ftell functions do not necessarily deal in pure byte offsets from the beginning of the file.

 107 views

143⟩ How can I read a binary data file properly?

How can I read a binary data file properly? I'm occasionally seeing 0x0a and 0x0d values getting garbled, and I seem to hit EOF prematurely if the data contains the value 0x1a.

When you're reading a binary data file, you should specify "rb" mode when calling fopen, to make sure that text file translations do not occur. Similarly, when writing binary data files, use "wb". (Under operating systems such as Unix which don't distinguish between text and binary files, "b" may not be required, but is harmless.)

Note that the text/binary distinction is made when you open the file: once a file is open, it doesn't matter which I/O calls you use on it.

 119 views

144⟩ How can I get back to the interactive keyboard if stdin is redirected?

I'm trying to write a program like ``more.'' How can I get back to the interactive keyboard if stdin is redirected?

There is no portable way of doing this. Under Unix, you can open the special file /dev/tty. Under MS-DOS, you can try opening the ``file'' CON, or use routines or BIOS calls such as getch which may go to the keyboard whether or not input is redirected.

 104 views

145⟩ Once I have used freopen, how can I get the original stdout (or stdin) back?

There isn't a good way. If you need to switch back, the best solution is not to have used freopen in the first place. Try using your own explicit output (or input) stream variable, which you can reassign at will, while leaving the original stdout (or stdin) undisturbed. For example, declare a global

FILE *ofp;

and replace all calls to printf( ... ) with fprintf(ofp, ... ). (Obviously, you'll have to check for calls to putchar and puts, too.) Then you can set ofp to stdout or to anything else.

You might wonder if you could skip freopen entirely, and do something like

FILE *savestdout = stdout; stdout = fopen(file, "w"); /* WRONG */

leaving yourself able to restore stdout later by doing

stdout = savestdout; /* WRONG */

but code like this is not likely to work, because stdout (and stdin and stderr) are typically constants which cannot be reassigned (which is why freopen exists in the first place). It may be possible, in a nonportable way, to save away information about a stream before calling freopen to open some file in its place, such that the original stream can later be restored. The most straightforward and reliable way is to manipulate the underlying file descriptors using a system-specific call such as dup or dup2, if available Another is to copy or inspect the contents of the FILE structure, but this is exceedingly nonportable and unreliable.

 108 views

146⟩ How can I recover the file name given an open stream?

This problem is, in general, insoluble. Under Unix, for instance, a scan of the entire disk (perhaps involving special permissions) would theoretically be required, and would fail if the descriptor were connected to a pipe or referred to a deleted file (and could give a misleading answer for a file with multiple links). It is best to remember the names of files yourself as you open them (perhaps with a wrapper function around fopen).

 108 views

147⟩ If fflush wont work, what can I use to flush input?

If fflush wont work, what can I use to flush input?

C Interview Questions and Answers

(Continued from previous question...)

If fflush wont work, what can I use to flush input?

It depends on what you're trying to do. If you're trying to get rid of an unread newline or other unexpected input after calling scanf you really need to rewrite or replace the call to scanf. Alternatively, you can consume the rest of a partially-read line with a simple code fragment like

while((c = getchar()) != 'n' && c != EOF)

/* discard */ ;

(You may also be able to use the curses flushinp function.)

There is no standard way to discard unread characters from a stdio input stream. Some vendors do implement fflush so that fflush(stdin) discards unread characters, although portable programs cannot depend on this. (Some versions of the stdio library implement fpurge or fabort calls which do the same thing, but these aren't standard, either.) Note, too, that flushing stdio input buffers is not necessarily sufficient: unread characters can also accumulate in other, OS-level input buffers. If you're trying to actively discard input (perhaps in anticipation of issuing an unexpected prompt to confirm a destructive action, for which an accidentally-typed ``y'' could be disastrous), you'll have to use a system-specific technique to detect the presence of typed-ahead input; Keep in mind that users can become frustrated if you discard input that happened to be typed too quickly.

 114 views

148⟩ How can I insert or delete a line (or record) in the middle of a file?

In general, there is no way to do this. The usual solution is simply to rewrite the file.

When you find yourself needing to insert data into an existing file, here are a few alternatives you can try:

* Rearrange the data file so that you can append the new information at the end.

* Put the information in a second file.

* Leave some blank space (e.g. a line of 80 spaces, or a field like 0000000000) in the file when it is first written, and overwrite it later with the final information

* (This technique is most portable in binary mode; on some systems, overwriting a text file may truncate it.) * Use a database instead of a flat file.

Instead of actually deleting records, you might consider just marking them as deleted, and having the code which reads the file ignore them. (You could run a separate coalescion program once in a while to rewrite the file, finally discarding the deleted records. Or, if the records are all the same length, you could take the last record and use it to overwrite the record to be deleted, then truncate the file.)

 126 views

149⟩ Why does everyone say not to use gets?

Unlike fgets(), gets() cannot be told the size of the buffer it's to read into, so it cannot be prevented from overflowing that buffer if an input line is longer than expected--and Murphy's Law says that, sooner or later, a larger-than-expected input line will occur. (It's possible to convince yourself that, for some reason or another, input lines longer than some maximum are impossible, but it's also possible to be mistaken, and in any case it's just as easy to use fgets.)

The Standard fgets function is a vast improvement over gets(), although it's not perfect, either. (If long lines are a real possibility, their proper handling must be carefully considered.)

One other difference between fgets() and gets() is that fgets() retains the 'n', but it is straightforward to strip it out.for a code fragment illustrating the replacement of gets() with fgets().

 123 views

150⟩ What is the deal on sprintfs return value?

What's the deal on sprintf's return value? Is it an int or a char *?

The Standard says that it returns an int (the number of characters written, just like printf and fprintf). Once upon a time, in some C libraries, sprintf returned the char * value of its first argument, pointing to the completed result (i.e. analogous to strcpy's return value).

 99 views

151⟩ Why does everyone say not to use scanf? What should I use instead?

scanf has a number of problems, its %s format has the same problem that gets() has --it's hard to guarantee that the receiving buffer won't overflow.

More generally, scanf is designed for relatively structured, formatted input (its name is in fact derived from ``scan formatted''). If you pay attention, it will tell you whether it succeeded or failed, but it can tell you only approximately where it failed, and not at all how or why. You have very little opportunity to do any error recovery.

Yet interactive user input is the least structured input there is. A well-designed user interface will allow for the possibility of the user typing just about anything--not just letters or punctuation when digits were expected, but also more or fewer characters than were expected, or no characters at all (i.e. just the RETURN key), or premature EOF, or anything. It's nearly impossible to deal gracefully with all of these potential problems when using scanf; it's far easier to read entire lines (with fgets or the like), then interpret them, either using sscanf or some other techniques. (Functions like strtol, strtok, and atoi are often useful; If you do use any scanf variant, be sure to check the return value to make sure that the expected number of items were found. Also, if you use %s, be sure to guard against buffer overflow.

 108 views

152⟩ How can I read data from data files with particular formats?

How can I read data from data files with particular formats?

How can I read ten floats without having to use a jawbreaker scanf format

like "%f %f %f %f %f %f %f %f %f %f"?

How can I read an arbitrary number of fields from a line into an array?

In general, there are three main ways of parsing data lines:

1. Use fscanf or sscanf, with an appropriate format string. Despite the limitations mentioned in this section, the scanf family is quite powerful. Though whitespace-separated fields are always the easiest to deal with, scanf format strings can also be used with more compact, column oriented, FORTRAN-style data. For instance, the line

1234ABC5.678

could be read with "%d%3s%f".

, then deal with each field individually, perhaps with functions like atoi and atof. (Once the line is broken up, the code for handling the fields is much like the traditional code in main() for handling the argv array;

Break the line into fields separated by whitespace (or some other delimiter), using strtok or the equivalent This method is particularly useful for reading an arbitrary (i.e. not known in advance) number of fields from a line into an array.

Here is a simple example which copies a line of up to 10 floating-point numbers (separated by whitespace) into an array:

#define MAXARGS 10

char line[] = "1 2.3 4.5e6 789e10";

char *av[MAXARGS];

int ac, i;

double array[MAXARGS];

ac = makeargv(line, av, MAXARGS);

for(i = 0; i < ac; i++)

array[i] = atof(av[i]);

 97 views

153⟩ Why doesnt that code work?

Why doesn't the code

short int s;

scanf("%d", &s);

work?

When converting %d, scanf expects a pointer to an int. To convert to a short int, use %hd .

 111 views

154⟩ Why does the call char scanf work?

Why does the call

char s[30];

scanf("%s", s);

work? I thought you always needed an & on each variable passed to scanf.

You always need a pointer; you don't necessarily need an explicit &. When you pass an array to scanf, you do not need the &, because arrays are always passed to functions as pointers, whether you use & or not.

 112 views

155⟩ Why doesnt this code work?

Why doesn't this code:

double d;

scanf("%f", &d);

work?

Unlike printf, scanf uses %lf for values of type double, and %f for float.%f tells scanf to expect a pointer-to-float, not the pointer-to-double you gave it. Either use %lf, or declare the receiving variable as a float.

 114 views

156⟩ Why doesnt the call scanf work?

Why doesn't the call scanf("%d", i) work?

The arguments you pass to scanf must always be pointers: for each value converted, scanf ``returns'' it by filling in one of the locations you've passed pointers to. To fix the fragment above, change it to scanf("%d", &i) .

 115 views

157⟩ Why doesnt long int work?

Why doesn't

long int n = 123456;

printf("%dn", n);

work?

Whenever you print long ints you must use the l (lower case letter ``ell'') modifier in the printf format (e.g. %ld). printf can't know the types of the arguments which you've passed to it, so you must let it know by using the correct format specifiers.

 115 views

158⟩ What is wrong with this code?

What's wrong with this code?

char c;

while((c = getchar()) != EOF) ...

For one thing, the variable to hold getchar's return value must be an int. EOF is an ``out of band'' return value from getchar: it is distinct from all possible char values which getchar can return. (On modern systems, it does not reflect any actual end-of-file character stored in a file; it is a signal that no more characters are available.) getchar's return value must be stored in a variable larger than char so that it can hold all possible char values, and EOF.

Two failure modes are possible if, as in the fragment above, getchar's return value is assigned to a char.

1. If type char is signed, and if EOF is defined (as is usual) as -1, the character with the decimal value 255 ('377' or 'xff' in C) will be sign-extended and will compare equal to EOF, prematurely terminating the input.

2. If type char is unsigned, an actual EOF value will be truncated (by having its higher-order bits discarded, probably resulting in 255 or 0xff) and will not be recognized as EOF, resulting in effectively infinite input.

The bug can go undetected for a long time, however, if chars are signed and if the input is all 7-bit characters. (Whether plain char is signed or unsigned is implementation-defined.)

 101 views

159⟩ What was noalias and what ever happened to it?

noalias was another type qualifier, in the same syntactic class as const and volatile, which was intended to assert that an object was not pointed to (``aliased'') by other pointers. The primary application, which is an important one, would have been for the formal parameters of functions designed to perform computations on large arrays. A compiler cannot usually take advantage of vectorization or other parallelization hardware (on supercomputers which have it) unless it can ensure that the source and destination arrays do not overlap.

The noalias keyword was not backed up by any ``prior art,'' and it was introduced late in the review and approval process. It was surprisingly difficult to define precisely and explain coherently, and sparked widespread, acrimonious debate, including a scathing pan by Dennis Ritchie. It had far-ranging implications, particularly for several standard library interfaces, for which easy fixes were not readily apparent.

Because of the criticism and the difficulty of defining noalias well, the Committee declined to adopt it, in spite of its superficial attractions. (When writing a standard, features cannot be introduced halfway; their full integration, and all implications, must be understood.) The need for an explicit mechanism to support parallel implementation of non-overlapping operations remains unfilled (although some work is being done on the problem)

 100 views

160⟩ What does the message "Automatic aggregate intialization is an ANSI feature" mean?

What does the message Automatic aggregate intialization is an ANSI feature'' mean? My compiler is complaining about valid ANSI code.

Messages like these are typically emitted by pre-ANSI compilers which have been upgraded just enough to detect (but not properly translate) new C features which were introduced with the ANSI Standard. The implication of the message is that you should pay your vendor more money for a copy of their real ANSI C compiler.

 111 views