C Programming/stdio.h - Wikibooks, open books for an open world (2023)

The C programming language provides many standard library functions for file input and output. These functions make up the bulk of the C standard library header <stdio.h>.

The I/O functionality of C is fairly low-level by modern standards; C abstracts all file operations into operations on streams of bytes, which may be "input streams" or "output streams". Unlike some earlier programming languages, C has no direct support for random-access data files; to read from a record in the middle of a file, the programmer must create a stream, seek to the middle of the file, and then read bytes in sequence from the stream.

The stream model of file I/O was popularized by the Unix operating system, which was developed concurrently with the C programming language itself. The vast majority of modern operating systems have inherited streams from Unix, and many languages in the C programming language family have inherited C's file I/O interface with few if any changes (for example, PHP). The C++ standard library reflects the "stream" concept in its syntax; see iostream.


  • 1 Function overview
  • 2 Reading from a stream using fgetc
    • 2.1 EOF pitfall
  • 3 fwrite
    • 3.1 Writing a file using fwrite
  • 4 Writing to a stream using fputc
  • 5 Example usage
  • 6 References

Function overview[edit | edit source]

Main article: C Programming/stdio.h/Function reference

(Video) C Programming for Beginners | Full Course

Most of the C file input/output functions are defined in /stdio.h (/cstdio header in C++).

File access
  • fopen - opens a file
  • freopen - opens a different file with an existing stream
  • fflush - synchronizes an output stream with the actual file
  • fclose - closes a file
  • setbuf - sets the buffer for a file stream
  • setvbuf - sets the buffer and its size for a file stream
  • fwide - switches a file stream between wide character I/O and narrow character I/O
Direct input/output
  • fread - reads from a file
  • fwrite - writes to a file
Unformatted input/output
Narrow character
  • fgetc, getc - reads a character from a file stream
  • fgets - reads a character string from a file stream
  • fputc, putc - writes a character to a file stream
  • fputs - writes a character string to a file stream
  • getchar - reads a character from stdin
  • gets - reads a character string from stdin
  • putchar - writes a character to stdout
  • puts - writes a character string to stdout
  • ungetc - puts a character back into a file stream
Wide character
  • fgetwc, getwc - reads a wide character from a file stream
  • fgetws - reads a wide character string from a file stream
  • fputwc, putwc - writes a wide character to a file stream
  • fputws - writes a wide character string to a file stream
  • getwchar - reads a wide character from stdin
  • putwchar - writes a wide character to stdout
  • ungetwc - puts a wide character back into a file stream
Formatted input/output
Narrow character
  • scanf, fscanf, sscanf - reads formatted input from stdin, a file stream or a buffer
  • vscanf, vfscanf, wsscanf - reads formatted input from stdin, a file stream or a buffer using variable argument list
  • printf, fprintf, sprintf, snprintf - prints formatted output to stdout, a file stream or a buffer
  • vprintf, vfprintf, vsprintf, vsnprintf - prints formatted output to stdout, a file stream, or a buffer using variable argument list
Wide character
  • wscanf, fwscanf, swscanf - reads formatted wide character input from stdin, a file stream or a buffer
  • vwscanf, vfwscanf, vswscanf - reads formatted wide character input from stdin, a file stream or a buffer using variable argument list
  • wprintf, fwprintf, swprintf - prints formatted wide character output to stdout, a file stream or a buffer
  • vwprintf, vfwprintf, vswprintf - prints formatted wide character output to stdout, a file sttream or a buffer using variable argument list
File positioning
  • ftell - returns the current file position indicator
  • fgetpos - gets the file position indicator
  • fseek - moves the file position indicator to a specific location in a file
  • fsetpos - moves the file position indicator to a specific location in a file
  • rewind - moves the file position indicator to the beginning in a file
Error handling
  • clearerr - clears errors
  • feof - checks for the end-of-file
  • ferror - checks for a file error
  • perror - displays a character string corresponding of the current error to stderr
Operations on files
  • remove - erases a file
  • rename - renames a file
  • tmpfile - returns a pointer to a temporary file
  • tmpnam - returns a unique filename

Reading from a stream using fgetc[edit | edit source]

The fgetc function is used to read a character from a stream.

int fgetc(FILE *fp);

If successful, fgetc returns the next byte or character from the stream (depending on whether the file is "binary" or "text", as discussed under fopen above). If unsuccessful, fgetc returns EOF. (The specific type of error can be determined by calling ferror or feof with the file pointer.)

The standard macro getc, also defined in <stdio.h>, behaves in almost the same way as fgetc, except that—being a macro—it may evaluate its arguments more than once.

The standard function getchar, also defined in <stdio.h>, takes no arguments, and is equivalent to getc(stdin).

EOF pitfall[edit | edit source]

A mistake when using fgetc, getc, or getchar is to assign the result to a variable of type char before comparing it to EOF. The following code fragments exhibit this mistake, and then show the correct approach (using type int):

(Video) C Programming Tutorial For Beginners: Learn C In Hindi

char c;while ((c = getchar()) != EOF) putchar(c);
int c; /* This will hold the EOF value */while ((c = getchar()) != EOF) putchar(c);

Consider a system in which the type char is 8bits wide, representing 256different values. getchar may return any of the 256possible characters, and it also may return EOF to indicate end-of-file, for a total of 257 different possible return values.

When getchar's result is assigned to a char, which can represent only 256 different values, there is necessarily some loss of information—when packing 257items into 256slots, there must be a collision. The EOF value, when converted to char, becomes indistinguishable from whichever one of the 256 characters shares its numerical value. If that character is found in the file, the above example may mistake it for an end-of-file indicator; or, just as bad, if type char is unsigned, then because EOF is negative, it can never be equal to any unsigned char, so the above example will not terminate at end-of-file. It will loop forever, repeatedly printing the character which results from converting EOF to char.

However, this looping failure mode does not occur if the char definition is signed (C makes the signedness of the default char type implementation-dependent),[1] assuming the commonly used EOF value of -1. However, the fundamental issue remains that if the EOF value is defined outside of the range of the char type, when assigned to a char that value is sliced and will no longer match the full EOF value necessary to exit the loop. On the other hand, if EOF is within range of char, this guarantees a collision between EOF and a char value. Thus, regardless of how system types are defined, never use char types when testing against EOF.

On systems where int and char are the same size (i.e., systems incompatible with minimally the POSIX and C99 standards), even the "good" example will suffer from the indistinguishability of EOF and some character's value. The proper way to handle this situation is to check feof and ferror after getchar returns EOF. If feof indicates that end-of-file has not been reached, and ferror indicates that no errors have occurred, then the EOF returned by getchar can be assumed to represent an actual character. These extra checks are rarely done, because most programmers assume that their code will never need to run on one of these "big char" systems. Another way is to use a compile-time assertion to make sure that UINT_MAX > UCHAR_MAX, which at least prevents a program with such an assumption from compiling in such a system.

fwrite[edit | edit source]

In the C programming language, the fread and fwrite functions respectively provide the file operations of input and output. fread and fwrite are declared in <stdio.h>.

Writing a file using fwrite[edit | edit source]

fwrite is defined as

size_t fwrite (const void *array, size_t size, size_t count, FILE *stream);
(Video) C Programming Tutorial for Beginners

fwrite function writes a block of data to the stream. It will write an array of count elements to the current position in the stream. For each element, it will write size bytes. The position indicator of the stream will be advanced by the number of bytes written successfully.

The function will return the number of elements written successfully. The return value will be equal to count if the write completes successfully. In case of a write error, the return value will be less than count.

The following program opens a file named sample.txt, writes a string of characters to the file, then closes it.

#include <stdio.h>#include <string.h>#include <stdlib.h>int main(void){ FILE *fp; size_t count; const char *str = "hello\n"; fp = fopen("sample.txt", "w"); if(fp == NULL) { perror("failed to open sample.txt"); return EXIT_FAILURE; } count = fwrite(str, 1, strlen(str), fp); printf("Wrote %zu bytes. fclose(fp) %s.\n", count, fclose(fp) == 0 ? "succeeded" : "failed"); return EXIT_SUCCESS;}

Writing to a stream using fputc[edit | edit source]

The fputc function is used to write a character to a stream.

int fputc(int c, FILE *fp);

The parameter c is silently converted to an unsigned char before being output. If successful, fputc returns the character written. If unsuccessful, fputc returns EOF.

(Video) C Language Tutorial for Beginners (with Notes & Practice Questions)

The standard macro putc, also defined in <stdio.h>, behaves in almost the same way as fputc, except that—being a macro—it may evaluate its arguments more than once.

The standard function putchar, also defined in <stdio.h>, takes only the first argument, and is equivalent to putc(c, stdout) where c is that argument.

Example usage[edit | edit source]

The following C program opens a binary file called myfile, reads five bytes from it, and then closes the file.

#include <stdio.h>#include <stdlib.h>int main(void){ const int count = 5; /* count of bytes to read from file */ char buffer[count] = {0}; /* initialized to zeroes */ int i, rc; FILE *fp = fopen("myfile", "rb"); if (fp == NULL) { perror("Failed to open file \"myfile\""); return EXIT_FAILURE; } for (i = 0; (rc = getc(fp)) != EOF && i < count; buffer[i++] = rc) ; fclose(fp); if (i == count) { puts("The bytes read were..."); for (i = 0; i < count; i++) printf("%x ", buffer[i]); puts(""); } else fputs("There was an error reading the file.\n", stderr); return EXIT_SUCCESS;}

References[edit | edit source]

  1. C99 §6.2.5/15


What's the difference between Iostream and Stdio? ›

First off, iostream is part of the C++ standard library, and stdio. h is part of the C standard library. While stdio. h will work in C++ it does not provide everything that iostream includes as iostream is specifically for C++.

What is the use of Stdio H in C programming? ›

The stdio. h header file allows us to perform input and output operations in C. The functions like printf() and scanf() are used to display output and take input from a user, respectively. This library allows us to communicate with users easily.

Does C language have libraries? ›

The C standard library or libc is the standard library for the C programming language, as specified in the ISO C standard. Starting from the original ANSI C standard, it was developed at the same time as the C library POSIX specification, which is a superset of it.

What is a C library What is it good for? ›

A library in C is a collection of header files, exposed for use by other programs. The library therefore consists of an interface expressed in a . h file (named the "header") and an implementation expressed in a . c file.

Is iostream faster than stdio? ›

The results

Here, everything is obvious. stdio is a lot faster than iostreams. It is notable that printf() / scanf() are even faster than the custom-written functions for int (but see addendum below). puts() / gets() are faster than printf() / scanf() on strings — this is understandable.

What can I use instead of iostream in C? ›

  1. If you don't want to use iostreams, your alternatives are C-style stdio and low level OS-specific functions like write() or WriteFile() . ...
  2. In addition to the C-style IO and the OS-specific IO, you can use other libraries (which will in turn use C-style IO, iostreams, or OS-specific IO).
Dec 7, 2018

Do I need to include Stdio? ›

The stdio. h header file should be included in our source code if we intend to utilise the printf or scanf functions in our program. Otherwise, the software will give an error or warning stating that there was an implicit declaration of the built-in function "printf," which it doesn't know what printf or scanf is.

Does C++ have Stdio? ›

These are not part of the C++ standard. The header <iostream. h> is replaced by <iostream> in standard C++, ratified in 1998. (Almost 22 years ago now!)

Why do we use void main in C? ›

void main() A void keyword is used to reference an empty data type. We can use the void keyword as the return type of the main function in c to depict that the function is not returning any value.

Does Microsoft use C language? ›

C++: C++ is the workhorse language at Microsoft, which uses C++ to build many of its core applications. C++ is used to create computer programs and is one of the most used languages in game development. It's the core language in many operating systems, browsers, and games.

Is C language still needed? ›

C exists everywhere in the modern world. A lot of applications, including Microsoft Windows, run on C. Even Python, one of the most popular languages, was built on C. Modern applications add new features implemented using high-level languages, but a lot of their existing functionalities use C.

What are the 2 types of libraries used in C? ›

There are two types of libraries in C static and dynamic.

What is the most used function in C? ›

The printf() function is the most used function in the C language. This function is defined in the stdio. h header file and is used to show output on the console (standard output).

What is the difference between C library and C++ library? ›

C++ runtime library contains functions and objects supplied in C++, such as cout, fstream and so on. C runtime library contains C functions such as printf, scanf, fopen, and so on. They're part of standard library, not runtime library.

What is the difference between C and C++ library? ›

C is a structural or procedural programming language that was used for system applications and low-level programming applications. Whereas C++ is an object-oriented programming language having some additional features like Encapsulation, Data Hiding, Data Abstraction, Inheritance, Polymorphism, etc.

Which one is faster between Python and C++? ›

C++ is faster than Python because it is statically typed, which leads to a faster compilation of code. Python is slower than C++, it supports dynamic typing, and it also uses the interpreter, which makes the process of compilation slower.

Why Fortran is faster than C? ›

Fortran semantics say that function arguments never alias and there is an array type, where in C arrays are pointers. This is why Fortran is often faster than C.

Is Java compilation faster than C++? ›

In contrast, a program written in C++ gets compiled directly into machine code -- without an intermediary translation required at runtime. This is one reason why C++ programs tend to perform faster than those written in Java.

What is the difference between Cin and cout? ›

cin is an object of the input stream and is used to take input from input streams like files, console, etc. cout is an object of the output stream that is used to show output. Basically, cin is an input statement while cout is an output statement. They also use different operators.

What are three different C++ classes that can be used to create input streams? ›

Let's deep dive into the four essential stream classes:
  • The istream class. This class is a general-purpose input stream and is used to read input from various sources, including the console and files. ...
  • The ifstream class. ...
  • The ostream class. ...
  • The ofstream class.
Apr 17, 2023

Why is it called iostream? ›

iostream stands for standard input-output stream. #include iostream declares objects that control reading from and writing to the standard streams. In other words, the iostream library is an object-oriented library that provides input and output functionality using streams.

Can we write C program without include? ›

Yes you can wirte a program without #include , but it will increase the complexity of the programmer means user have to write down all the functions manually he want to use.It takes a lot of time and careful attention while write long programs.

Which header file is necessary in C? ›

Every C program should necessarily contain the header file <stdio. h> which stands for standard input and output used to take input with the help of scanf() function and display the output using printf() function.

Can C program successfully without including header files? ›

So, in short, the answer is yes. We can compile C program without header file.

Is C++ not used anymore? ›

So, the answer is no. C++ isn't going away any time soon. C++ is now one of the most widely used computer languages, with a wide range of applications. Python, Java, and web programming are all intriguing career paths, but C++ programmers are often overlooked and mistakenly believed to be dead.

Does anyone still use C++? ›

It is a versatile language, so it remains in high demand amongst professionals, such as software developers, game developers, C++ analysts and backend developers, etc. As per the TIOBE index of 2022, C++ lies at 4th position in the world's most popular language.

Will all C code run in C++? ›

Oracle Developer Studio C and C++ compilers use compatible headers, and use the same C runtime library. They are fully compatible.

What are the key words in C? ›

C reserved keywords
4 more rows

What is %d in C? ›

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.

What is the difference between void and main in C? ›

The main() is a function from where any C Program starts execution and void is a keyword which is used in the place of function's return type which means the function will not return any value at the point of call. Main () is the function from where program execution starts. And the void is the empty return type.

Are C programmers in demand? ›

Despite the rise of new programming languages, C remains in high demand, and many tech companies are looking for developers who are fluent in it. C is a versatile language that gives the programmer a lot of control, and its popularity attests to its effectiveness and dependability.

Why C is not considered as high-level language? ›

C and C++ are now considered low-level languages because they have no automatic memory management.

Is C still used in 2023? ›

Python and C will continue to be popular with programmers, while Java and PHP will slip in popularity.

How long does it take to learn C programming? ›

If you are a beginner with no programming experience, you should expect it to take at least three months to learn the basics. If you have programmed before, it may only take you a month or two. To build mastery in C++, you should expect to spend at least two years working on improving your skills a little each day.

Does C programming have future? ›

The C programmers not only work in the field of computer only, but they can also pursue their career in Education, teaching, Government sectors, etc. as some of the programmers have a different specialization like in system analysis, project management, information systems, etc.

What is the name of the most common library file in C? ›

stdlib. h − This file contains common functions which are used in the C programs.

Are all Python libraries written in C? ›

So, we can say that the Python interpreter is written in the C programming language. The implementation of Python code can also be done in other languages. Some of these implementations are Jython, PyPy, and IronPython. However, CPython is the most commonly used implementation of Python.

What library for read and write in C? ›

The C standard I/O library provides the functions fgetc() and fputc() for reading and writing characters, respectively. How they work is very simple. Both operate with file streams, or more commonly known in C, the FILE type.

How many functions can you have in C? ›

There are two types of function in C programming: Standard library functions. User-defined functions.

Which function is must in every C program? ›

Every C program has a primary function that must be named main . The main function serves as the starting point for program execution.

Can you use libraries in C? ›

C Standard library functions or simply C Library functions are inbuilt functions in C programming. The prototype and data definitions of these functions are present in their respective header files. To use these functions we need to include the header file in our program.

Why are libraries written in C? ›

The standard system libraries for input/output, networking, string processing, mathematics, security, data encoding, and so on are likewise written mainly in C. To write a library in C is therefore to write in Linux's native language. Moreover, C sets the mark for performance among high-level languages.

Should I learn C or C++? ›

Compared to C, C++ has significantly more libraries and functions to use. If you're working with complex software, C++ is a better fit because you have more libraries to rely on. Thinking practically, having knowledge of C++ is often a requirement for a variety of programming roles.

What is the difference between C and C++ for beginners? ›

There is a major difference between C and C++. The C language is a procedural one that provides no support for objects and classes. On the other hand, the C++ language is a combination of object-oriented and procedural programming languages.

Which is harder C or C++? ›

Q #2) Which is more difficult C or C++? Or Which is better C or C++? Answers: Actually, both are difficult and both are easy. C++ is built upon C and thus supports all features of C and also, it has object-oriented programming features.

Is iostream used in C or C++? ›

The standard iostream classes are available only in standard mode, and are contained in the C++ standard library, libCstd .

Is iostream needed in C++? ›

To perform any input and output operations in C++, we need to use iostream header files. Without an <iostream> header file, we cannot take input from the user or print any output. Syntax of <iostream> header file: #include <iostream.

What is the difference between C and C++? ›

C is a structural or procedural programming language that was used for system applications and low-level programming applications. Whereas C++ is an object-oriented programming language having some additional features like Encapsulation, Data Hiding, Data Abstraction, Inheritance, Polymorphism, etc.

What is the difference between iostream and namespace? ›

What is the difference between #include<iostream> and using namespace std?? iostream is a library that have function like (cin cout int float...) Using namespace std is a shortcut if you want to make your code more clean.

Does iostream exist in C? ›

C++ input/output streams are primarily defined by iostream , a header file that is part of the C++ standard library (the name stands for Input/Output Stream). In C++ and its predecessor, the C programming language, there is no special syntax for streaming data input or output.

Why do programmers use #include iostream in C++? ›

#include iostream declares objects that control reading from and writing to the standard streams. In other words, the iostream library is an object-oriented library that provides input and output functionality using streams. A stream is a sequence of bytes. You can think of it as an abstraction representing a device.

Why do we use iostream instead of iostream h? ›

Answers. iostream. h is deprecated and not a standard header. It was used in older programs before C++ was standardized, Functions like cout were defined inside iostream.

What happens if you don't include iostream? ›

this is because IOSTREAM stands for input-output stream and C++ language is requires to tell it the functions you gonna use in your program which is done by including the “header files” and if you skip iostream header file then the written on this file will not have their definitions to work on and as result you'll get ...

What should I include in my iostream? ›

iostream is the header file which contains all the functions of program like cout, cin etc. and #include tells the preprocessor to include these header file in the program. It is a header file in c++which is responsible for input and output stream.

Why do people use C and not C++? ›

Picking C over C++ is a way for developers and those who maintain their code to embrace enforced minimalism and avoid tangling with the excesses of C++. Of course, C++ has a rich set of high-level features for good reason.

Why do people use C++ over C? ›

Compared to C, C++ has significantly more libraries and functions to use. If you're working with complex software, C++ is a better fit because you have more libraries to rely on. Thinking practically, having knowledge of C++ is often a requirement for a variety of programming roles.

Do I need to learn C before C++? ›

As much as you may think C and C++ are similar, they aren't. There's no exact order of learning any of these two languages. What may work in one language may not work in the other, although they are basically one derived from the other. C++ is a much larger, much more complex language than C.

Should I use namespace or class C++? ›

Difference between namespace and class in C++

Classes are basically extended version of structures. Classes can contain data members and functions as members, but namespaces can contain variables and functions by grouping them into one. The namespaces cannot be created as objects.

Why is using namespace std a bad practice? ›

Using namespace std; can also lead to code that is difficult to maintain and debug. This is because it is not always clear where elements are coming from. For example, if a developer uses the name “string” without qualifying it, it could be referring to either the std::string class or a custom string class.

What is the difference between namespace and library in C++? ›

Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. In programming, a library is a collection of precompiled routines that a program can use.


1. How to Run C in Visual Studio Code on Mac OS Apple Macbook M1
(Tech Decode Tutorials)
2. C++ Programming Course - Beginner to Advanced
3. First C Program | Easiest way to Understand C Programming
(Gate Smashers)
4. C Programming Tutorial | In Hindi | Easy to Learn | PRIDE COMPUTER EDUCATION
(Pride Educare)
5. OpenGL Course - Create 3D and 2D Graphics With C++
6. Getting Started with Texmaker IDE for LaTeX2ε
Top Articles
Latest Posts
Article information

Author: Kimberely Baumbach CPA

Last Updated: 25/05/2023

Views: 5656

Rating: 4 / 5 (41 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Kimberely Baumbach CPA

Birthday: 1996-01-14

Address: 8381 Boyce Course, Imeldachester, ND 74681

Phone: +3571286597580

Job: Product Banking Analyst

Hobby: Cosplaying, Inline skating, Amateur radio, Baton twirling, Mountaineering, Flying, Archery

Introduction: My name is Kimberely Baumbach CPA, I am a gorgeous, bright, charming, encouraging, zealous, lively, good person who loves writing and wants to share my knowledge and understanding with you.