C stdio.h Functions

Explore all C stdio.h functions in one place with clear descriptions, example programs, and outputs. Learn printf, scanf, file handling functions, and more for fast and effective C programming.

Function

Description

Example Code

Output

printf()

Prints formatted output to the console

printf("Hi %d",10);

Hi 10

scanf()

Reads formatted input from user

scanf("%d",&n);

User enters: 25

getchar()

Reads one character from user input

char c=getchar();

User enters: A

putchar(ch)

Outputs a single character to console

putchar('X');

X

puts(str)

Prints a string + newline

puts("Hello");

Hello

getc(fp)

Same as fgetc()

ch=getc(fp);

e.g., H

putc(ch,fp)

Same as fputc()

putc('B',fp);

B written

fopen("file","mode")

Opens a file and returns a file pointer

fp=fopen("data.txt","w");

(File opened)

fclose(fp)

Closes an open file

FILE *fp=fopen("a.txt","r"); fclose(fp);

(File closed successfully)

fgetc(fp)

Reads a single character from file

ch=fgetc(fp);

e.g., A

fgets(str,n,fp)

Reads a line/string from file

fgets(str,50,fp);

e.g., Hello world

fputc(ch,fp)

Writes a character into a file

fputc('A',fp);

A written

fputs(str,fp)

Writes a string into a file

fputs("Hello",fp);

Hello written

fprintf(fp, "text")

Writes formatted text into file

fprintf(fp,"Age=%d",20);

(Written to file)

fscanf(fp,"%d",&x)

Reads formatted data from a file

fscanf(fp,"%d",&num);

e.g., 10

fread(ptr,size,n,fp)

Reads block of data from file

fread(a,sizeof(int),5,fp);

(Reads array)

fwrite(ptr,size,n,fp)

Writes block of data to file

fwrite(a,sizeof(int),5,fp);

(Writes array)

fseek(fp, offset, origin)

Moves file pointer

fseek(fp,0,SEEK_END);

(Pointer moved)

ftell(fp)

Returns current file position

printf("%ld",ftell(fp));

e.g., 20

rewind(fp)

Moves pointer to file beginning

rewind(fp);

Position = 0

feof(fp)

True if end of file reached

while(!feof(fp)) { fgetc(fp); }

(EOF detected)

ferror(fp)

True if a file error occurred

if(ferror(fp)) printf("Error");

Error (if error exists)

remove("file")

Deletes a file

remove("a.txt");

(File deleted)

rename("old","new")

Renames a file

rename("a.txt","b.txt");

(Renamed)

snprintf(str,n,"fmt")

Safe formatted output to array

snprintf(str,10,"Hi %d",5);

Hi 5

sprintf(str,"fmt")

Writes formatted output to array

sprintf(str,"Age=%d",20);

Age=20

Leave a Reply

Your email address will not be published. Required fields are marked *