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

61⟩ How can I find out how much memory is available?

Your operating system may provide a routine which returns this information, but it's quite system-dependent. (Also, the number may vary over time.) If you're trying to predict whether you'll be able to allocate a certain amount of memory, just try it--call malloc (requesting that amount) and check the return value.

 106 views

62⟩ How do I create a directory? How do I remove a directory (and its contents)?

If your operating system supports these services, they are likely to be provided in C via functions named mkdir and rmdir. Removing a directory's contents as well will require listing them and calling remove . If you don't have these C functions available, try system along with your operating system's delete command(s).

 93 views

63⟩ How can I allocate arrays or structures bigger than 64K?

A reasonable computer ought to give you transparent access to all available memory. If you're not so lucky, you'll either have to rethink your program's use of memory, or use various system-specific techniques.

64K is (still) a pretty big chunk of memory. No matter how much memory your computer has available, it's asking a lot to be able to allocate huge amounts of it contiguously. (The C Standard does not guarantee that single objects can be 32K or larger, or 64K for C99.) Often it's a good idea to use data structures which don't require that all memory be contiguous. For dynamically-allocated multidimensional arrays, you can use pointers to pointers, Instead of a large array of structures, you can use a linked list, or an array of pointers to structures.

If you're using a PC-compatible (8086-based) system, and running up against a 64K or 640K limit, consider using ``huge'' memory model, or expanded or extended memory, or malloc variants such as halloc or farmalloc, or a 32-bit ``flat'' compiler , or some kind of a DOS extender, or another operating system.

 101 views

64⟩ How can I read a directory in a C program?

See if you can use the opendir and readdir functions, which are part of the POSIX standard and are available on most Unix variants. Implementations also exist for MS-DOS, VMS, and other systems. (MS-DOS also has FINDFIRST and FINDNEXT routines which do essentially the same thing, and MS Windows has FindFirstFile and FindNextFile.) readdir returns just the file names; if you need more information about the file, try calling stat. To match filenames to some wildcard pattern,

Here is a tiny example which lists the files in the current directory:

#include <stdio.h>

#include <sys/types.h>

#include <dirent.h>

main()

{

struct dirent *dp;

DIR *dfd = opendir(".");

if(dfd != NULL) {

while((dp = readdir(dfd)) != NULL)

printf("%sn", dp->d_name);

closedir(dfd);

}

return 0;

}

(On older systems, the header file to #include may be <direct.h> or <dir.h>, and the pointer returned by readdir may be a struct direct *. This example assumes that "." is a synonym for the current directory.)

In a pinch, you could use popen to call an operating system list-directory program, and read its output. (If you only need the filenames displayed to the user, you could conceivably use system

 82 views

65⟩ How can I find out how much free space is available on disk?

There is no portable way. Under some versions of Unix you can call statfs. Under MS-DOS, use interrupt 0x21 subfunction 0x36, or perhaps a routine such as diskfree. Another possibility is to use popen to invoke and read the output of a ``disk free'' command (df on Unix).

(Note that the amount of free space apparently available on a disk may not match the size of the largest file you can store, for all sorts of reasons.)

 105 views

66⟩ Why cant I open a file by its explicit path?

Why can't I open a file by its explicit path? The call

fopen("c:newdirfile.dat", "r")

is failing.

The file you actually requested--with the characters n and f in its name--probably doesn't exist, and isn't what you thought you were trying to open.

In character constants and string literals, the backslash is an escape character, giving special meaning to the character following it. In order for literal backslashes in a pathname to be passed through to fopen (or any other function) correctly, they have to be doubled, so that the first backslash in each pair quotes the second one:

fopen("c:newdirfile.dat", "r")

Alternatively, under MS-DOS, it turns out that forward slashes are also accepted as directory separators, so you could use

fopen("c:/newdir/file.dat", "r")

(Note, by the way, that header file names mentioned in preprocessor #include directives are not string literals, so you may not have to worry about backslashes there.)

 111 views

67⟩ fopen isnt letting me open files like "$HOME/.profile" and "~/.myrcfile".

fopen isn't letting me open files like "$HOME/.profile" and "~/.myrcfile".

Under Unix, at least, environment variables like $HOME, along with the home-directory notation involving the ~ character, are expanded by the shell, and there's no mechanism to perform these expansions automatically when you call fopen.

 81 views

68⟩ How can I increase the allowable number of simultaneously open files?

Q; I'm getting an error, ``Too many open files''. How can I increase the allowable number of simultaneously open files?

A: There are typically at least two resource limitations on the number of simultaneously open files: the number of low-level ``file descriptors'' or ``file handles'' available in the operating system, and the number of FILE structures available in the stdio library. Both must be sufficient. Under MS-DOS systems, you can control the number of operating system file handles with a line in CONFIG.SYS. Some compilers come with instructions (and perhaps a source file or two) for increasing the number of stdio FILE structures.

 99 views

69⟩ How do I copy files?

Either use system() to invoke your operating system's copy utility, or open the source and destination files (using fopen or some lower-level file-opening system call), read characters or blocks of characters from the source file, and write them to the destination file. Here is a simple example:

#include <stdio.h>

int copyfile(char *fromfile, char *tofile)

{

FILE *ifp, *ofp;

int c;

if((ifp = fopen(fromfile, "r")) == NULL) return -1;

if((ofp = fopen(tofile, "w")) == NULL) { fclose(ifp); return -1; }

while((c = getc(ifp)) != EOF)

putc(c, ofp);

fclose(ifp);

fclose(ofp);

return 0;

}

To copy a block at a time, rewrite the inner loop as

while((r = fread(buf, 1, sizeof(buf), ifp))> 0)

fwrite(buf, 1, r, ofp);

where r is an int and buf is a suitably-sized array of char.

 117 views

71⟩ ow 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.)

 94 views

72⟩ How can I recover the file name given an open stream or file descriptor?

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).

 168 views

73⟩ How can I find out the size of a file, prior to reading it in?

If the ``size of a file'' is the number of characters you'll be able to read from it in C (or which were written to it by a previous program), it can be difficult or impossible to determine this number exactly (other than by reading the whole file).

Under Unix, the stat call (specifically, the st_size field of the stat structure) will give you an exact answer.Several other systems supply a Unix-like stat call, but the sizes reported for text files may be approximate (due to differing end-of-line representations; . You can open the file and use fstat, or fseek to the end of the file and then use ftell, but these tend to have the same problems: fstat is not portable, and generally tells you the same thing stat tells you; ftell is not guaranteed to return a byte count except for binary files (but, strictly speaking, binary files don't necessarily support fseek to SEEK_END at all). Some systems provide functions called filesize or filelength, but these are obviously not portable, either.

Are you sure you have to determine the file's size in advance? Since the most accurate way of determining the size of a file as a C program will see it is to open the file and read it, perhaps you can rearrange the code to learn the size as it reads. (In general, your program should behave gracefully if the number of characters actually read does not match prior expectations, since any advance determination of the size might be approximate.)

 171 views

74⟩ How can I delete a file?

The Standard C Library function is remove. (This is therefore one of the few questions in this section for which the answer is not ``It's system-dependent.'') On older, pre-ANSI Unix systems, remove may not exist, in which case you can try unlink.

 183 views

75⟩ How can I check whether a file exists? I want to warn the user if a requested input file is missing.

It's surprisingly difficult to make this determination reliably and portably. Any test you make can be invalidated if the file is created or deleted (i.e. by some other process) between the time you make the test and the time you try to open the file.

Three possible test functions are stat, access, and fopen. (To make an approximate test using fopen, just open for reading and close immediately, although failure does not necessarily indicate nonexistence.) Of these, only fopen is widely portable, and access, where it exists, must be used carefully if the program uses the Unix set-UID feature. (If you have the choice, the best compromise is probably one of the stat functions.)

Rather than trying to predict in advance whether an operation such as opening a file will succeed, it's often better to try it, check the return value, and complain if it fails. (Obviously, this approach won't work if you're trying to avoid overwriting an existing file, unless you've got something like the O_EXCL file opening option available, which does just what you want in this case.)

 200 views

76⟩ How can I do graphics in C?

Once upon a time, Unix had a fairly nice little set of device-independent plot functions described in plot(3) and plot(5). The GNU libplot library, written by Robert Maier, maintains the same spirit and supports many modern plot devices; see http://www.gnu.org/software/plotutils/plotutils.html.

A modern, platform-independent graphics library (which also supports 3D graphics and animation) is OpenGL. Other graphics standards which may be of interest are GKS and PHIGS.

A modern, platform-independent graphics library (which also supports 3D graphics and animation) is OpenGL. Other graphics standards which may be of interest are GKS and PHIGS.

If you're programming for MS-DOS, you'll probably want to use libraries conforming to the VESA or BGI standards.

If you're trying to talk to a particular plotter, making it draw is usually a matter of sending it the appropriate escape sequences; The vendor may supply a C-callable library, or you may be able to find one on the net.

If you're programming for a particular window system (Macintosh, X windows, Microsoft Windows), you will use its facilities;

 177 views

78⟩ How can I access an I O board directly?

At one level, at least, it's quite simple: you have a device register which is actually wired up so that the bits written to it get coverted to actual voltage levels in the real world that you can do interesting things with. In general, there are two ways to get the bits in and out. (A particular I/O board will use one method or the other; you'll need to consult its documentation for details.)

1. If the device is accessed via a dedicated ``I/O port'', use system-specific functions to communicate with it. Under MS-DOS, for example, there were quasistandard ``inport'' and ``outport'' instructions.

2. If the device uses ``memory-mapped I/O'', that is, if the device register(s) are accessed as if they were normal memory at particular, known locations within the processor's addressing space, use contrived pointer variables to access those locations.

 188 views

79⟩ How can I do serial comm port I O?

How can I do serial (``comm'') port I/O?

It's system-dependent. Under Unix, you typically open, read, and write a device file in /dev, and use the facilities of the terminal driver to adjust its characteristics.Under MS-DOS, you can use the predefined stream stdaux, or a special file like COM1, or some primitive BIOS interrupts, or (if you require decent performance) any number of interrupt-driven serial I/O packages. Several netters recommend the book C Programmer's Guide to Serial Communications, by Joe Campbell.

 191 views

80⟩ How can I direct output to the printer?

Under Unix, either use popen to write to the lp or lpr program, or perhaps open a special file like /dev/lp. Under MS-DOS, write to the (nonstandard) predefined stdio stream stdprn, or open the special files PRN or LPT1. Under some circumstances, another (and perhaps the only) possibility is to use a window manager's screen-capture function, and print the resulting bitmap.

 194 views