Table of Contents

C Examples

Mithat Konar
Derived from Differences Between C and C++ by Robert Niemann
2020-05-03

Input/output

example00.c
/* Basic printf use. */
#include <stdio.h>
 
int main()
{
  int numSpoons = 5;
 
  printf( "I have %d spoons.\n", numSpoons );
 
  return 0;
}
example01.c
/* Basic scanf use. */
#include <stdio.h>
 
int main()
{
    int num;
 
    printf( "Please enter a number: " );
    scanf( "%d", &num );
    printf( "You entered %d\n", num );
 
    return 0;
}
example02.c
/* Common I/O format specifiers. */
#include <stdio.h>
 
int main()
{
  int dec = 5;
  char str[] = "abc";
  char ch = 's';
  float pi = 3.14;
 
  printf("%d %s %f %c\n", dec, str, pi,  ch);
 
  return 0;
}
example03.c
/* More I/O format specifiers. */
#include <stdio.h>
 
int main()
{
    char ch;
    int x;
    double y;
 
    printf("Enter a character, an integer, and a double:\n");
    scanf("%c %d %lf", &ch, &x, &y);
    printf("%c %d %lf\n", ch, x, y);
 
    return 0;
}

File access

example04.c
/* Writing a text file. */
#include <stdio.h>
 
int main()
{
    FILE *ptr_file;
    int x;
 
    ptr_file = fopen("output.txt", "w");
 
    if (!ptr_file)
        return 1;
 
    for (x = 1; x <= 10; x++)
    {
        fprintf(ptr_file,"%d\n", x);
    }
 
    fclose(ptr_file);
 
    return  0;
}
example05.c
/* Reading a text file. */
#include <stdio.h>
 
int main()
{
    FILE *ptr_file;
    char buf[1000];    /* can store strings up to 999 chars long */
 
    ptr_file = fopen("input.txt","r");
    if (!ptr_file)
    {
        return 1;
    }
 
    while (fgets(buf,1000, ptr_file) != NULL)
    {
        printf("%s",buf);
    }
 
    fclose(ptr_file);
 
    return 0;
}