C scanf() function : C Reference

Scanf : Reading or Accepting String From User in C

In C Programming we can use scanf function from stdio.h header file to read string. Scanf function is commonly used for accepting string.

Syntax for Accepting String :

scanf("%s",Name_Of_String_Variable);

Live Example :

#include<stdio.h>
void main()
{
char name[20];
printf("\nEnter the Name : ");
scanf("%s",name);
}

Explanation : Scanf Program

In the above program we are accepting string from user using scnaf() function. We cannot use string ampersand address operator in the scanf() because string itself can be referred by address.

Some Rules and Facts :

  1. Format Specifier %s is used for Accepting String
  2. Scanf() function accepts only String before Space
#include<stdio.h>
int main()
{
char name[20];
printf("\nEnter the Name : ");
scanf("%s",name);
printf("Name of the Company : %s",name);
return(0);
}

Output :

Enter the Name : Google Incl
Name of the Company : Google

We can use scanf to Accept String With Spaces. Just Replace above scanf statement with this following statement -

scanf("%[\^n]", name );

Read more about Reading String with spaces using scanf.

Why We does not need Ampersand Operator :

  1. Scanf() needs a pointer to the variable that will store input.
  2. In the case of a string, you need a pointer to an array of characters in memory big enough to store whatever string is read in.
  3. When you declare something like char var[100], you make space for 100 chars with name[0] referring to the first char and name[99] referring to the 100th char.
  4. The array name by itself evaluates to exactly the same thing as &name[0], which is a pointer to the first character of the sequence, exactly what is needed by scanf.
  5. So all you need to do is -
  6. scanf("%s", name);
    

C ferror() macro : C Reference

Ferror Macro :

  1. “ferror” is Macro.
  2. This tests if an error has occurred on a stream or not.
  3. Tests Give Stream for Read / Write Error.

Syntax :

int ferror(FILE *stream);
  • Return Type : Integer.
  • Parameter : File Stream

Live Example :

#include<stdio.h>
int main(void)
{
FILE *fp;
    fp = fopen("myfile.txt","w");
    if (ferror(fp)) {
           printf("Error has Occured");
           clearerr(stream);
   }
}

Return Value :

  1. If Error has Occurred : Returns [Non Zero Value]
  2. If Error has no Occurred : Returns [Zero]

Explanation of the Code :

We have opened file for writing purpose in write mode. Whenever we open file for writing then we have to check whether file is opened in writing mode or not. If not then Compiler will throw the error. ferror macro will check whether there is error while opening the stream or not.

if (ferror(fp)) {
           printf("Error has Occured");
           clearerr(stream);
   }

If we found any error then we are executing the exception or error handler code.

Summary :

TypeIt is Macro Not a function
PurposeTests if an error has occurred on a stream or not
Return ValueNon Zero Value if True
Zero Value if False

C memset() function : C Reference

Memset function is C Programming : string.h

  1. memset : MEMory SET
  2. It is used to fill the blocks of memory.
  3. Sets the first num bytes of the block of memory pointed by ptr to the specified value.

Syntax :

void * memset ( void * ptr, int value, size_t num );

Parameters Passed to the Function Memset :

ptr

Pointer to the block of memory to fill.

value

  • Value to be set.
  • The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.

num

Number of bytes to be set to the value.

Return Value

ptr is returned.

Live Example :

#include<stdio.h>
#include<string.h>
int main ()
{
  char str[] = "C Programming Language";
  memset (str,'-',6);
  puts (str);
  return 0;
}

Output :

------ramming Language

C allocmem() function : C Reference

Allocmem() : Allocates DOS memory segment in C [dos.h function]

  1. Allocates DOS memory segment
  2. Allocmem use the DOS system call 0x48 .
  3. It allocate a block of free memory
  4. It return the segment address of the allocated block.

Declaration :

int allocmem(unsigned size, unsigned *segp);

Parameters :

Parameter
What it does ?
size
The number of 16-byte paragraphs requested
segp
Pointer to a word that will be assigned the segment address of the newly allocated block

If not enough room is available,

  1. allocmem makes no assignment to the word *segp
  2. All allocated blocks are paragraph-aligned.

NOTE : malloc can’t coexist with either allocmem or _dos_allocmem.

Return Value :

  1. On success, allocmem returns -1
  2. On error, allocmem returns the size of the largest available block and sets both _doserrno and errno to ENOMEM (Not enough memory)

Live Example :

#include <dos.h>
#include <alloc.h>
#include <stdio.h>
int main(void)
{
  unsigned int size, segp;
  int stat;
  size = 64;                    /* (64 x 16) = 1024 bytes */
  stat = allocmem(size, &segp);
  if (stat == -1)
    printf("Allocated memory at segment: %x\n", segp);
  else
    printf("Failed: maximum number of paragraphs available is %u\n", stat);
  return 0;
}

C abswrite() function : C Reference

Abswrite() : Write absolute disk sectors in C [dos.h function]

Declaration : abswrite()

int abswrite(int drive,int nsects,long lsect,void *buffer);

Remarks:

  1. abswrite uses DOS interrupt 0x26 to read specific disk sectors.
  2. abswrite writes absolute disk sectors
  3. It ignores the logical structure of a disk and pay no attention to files, FATs, or directories.
  4. The number of sectors to read is limited to 64K or the size of the buffer, whichever is smaller.
  5. If used improperly, abswrite can overwrite files, directories, and FATs.

Parameters

Parameter
What It Is/Does ?
drive
Drive number to read (or write): 0 = A 1 = B etc.
nsects
Number of sectors to read (or write)
lsect
Beginning logical sector number
buffer
Memory address where the data is to be read (or written)

Return Value:

  1. On success, return 0.
  2. On error, return -1 and set errno to the value of the AX register returned by the system call.

C absread() function : C Reference

Absread() : Read absolute disk sectors in C [dos.h function]

Declaration : absread()

int absread(int drive,int nsects,long lsect,void *buffer);

Remarks:

  1. absread uses DOS interrupt 0x25 to read specific disk sectors.
  2. absread reads absolute disk sectors
  3. It ignores the logical structure of a disk and pay no attention to files, FATs, or directories.
  4. The number of sectors to read is limited to 64K or the size of the buffer, whichever is smaller.

Parameters

Parameter
What It Is/Does ?
drive
Drive number to read (or write): 0 = A 1 = B etc.
nsects
Number of sectors to read (or write)
lsect
Beginning logical sector number
buffer
Memory address where the data is to be read (or written)

Return Value:

  1. On success, return 0.
  2. On error, return -1 and set errno to the value of the AX register returned by the system call.

Live Example :

#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <dos.h>
int main(void)
{
  int i, strt, ch_out, sector;
  char buf[512];
  printf("Insert a diskette into drive A and press any key\n");
  getch();
  sector = 0;
  if (absread(0, 1, sector, &buf) != 0)
  {
     perror("Disk problem");
     exit(1);
  }
  printf("Read OK\n");
  strt = 3;
  for (i=0; i<80; i++)
  {
     ch_out = buf[strt+i];
     putchar(ch_out);
  }
  printf("\n");
  return(0);
}

Output :

Insert a diskette into drive A and press any key

*It will show this output in newer versions of PC those do not have Floppy Disk Drives.

C fopen() function : <stdio.h>

Opening file in C : fopen function (stdio.h Function)

Syntax of Declaring FILE pointer

FILE *fp;

Syntax of Opening file hello.txt

fp = fopen ("filename","mode");

How to open file in C ?

  1. fopen opens a stream
  2. fopen open a file and associate a stream with it.
  3. functions return a pointer that identifies the stream in subsequent operations.
  4. FILE will be opened for following purposes -
    • Reading data file
    • Writing on data file
    • Appending Content to the file

Explanation :

  1. In simple words fopen function will open file specified in the specified mode.
  2. We have different file opening modes in C Programming. [ Refer : File opening modes in C ].
  3. After opening file in the read mode fopen() will return the address of the structure that contains information needed for subsequent I/O on the file being opened.(i.e File Pointer)
  4. In order to store file pointer we have assigned return address to FILE pointer variable “fp“.
  5. e.g here fopen will open “file1.txt” in the “read” mode.
fp = fopen("file1.txt","r");

Live Example :

#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("INPUT.txt","r"); 
 while(1) 
  {
  ch = fgetc(fp); 
  if(ch == EOF ) 
     break ; 
  printf("%c",ch); 
  } 
fclose(fp); 
}

C getc macro : C Reference

getc macro : Read Character from Stream (stdio.h Header file)

  1. getc is a macro.
  2. getc accepts one character from a stream
  3. Header file : Stdio.h
  4. getc returns the next character on the given input stream .
  5. Getc increments the stream’s file pointer to point to the next character.
  6. getc returns the character read, after converting it to an int without sign extension.

Syntax :

int getc(FILE *stream);

Live Example :

int main(void) 
{
char ch;
printf("\nInput a character:");
/* read a character from the standard
   input stream */
ch = getc(stdin);
printf("\nThe character input was : '%c'", ch);
return 0;
}

Output :

Input a character : P
The character input was : 'P'

Another Live Example :

#include<stdio.h>
int main()
{
  int ch;
  FILE *fp;
  if (fp = fopen("file.txt", "rt"))
  {
    ch = getc(fp);
    while (ch != EOF)
    {
      printf("%c", ch);
      ch = getc(fp);
    }
    fclose(fp);
  }
  return 0;
}

Output :

It will read complete file till we get EOF

C getc() function : <stdio.h>

Fgetc function : get character from stream

What this function does ?

  1. Header File : Stdio.h
  2. fgetc gets a character from a stream
  3. fgetc returns the next character on the named input stream.
  4. It is a function not macro (getc is a macro)

Return Value :

EventReturn Value
On ErrorReturns Character read after converting it into integer without sign Extension
On SuccessEOF
On End of FileEOF

C Program to Read File Character by Character : Fgetc Function

#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("tmp.txt","r");
printf("Data inside File : ");
while(1)
 {
 ch = fgetc(fp);
 if(ch == EOF)
    break;
 printf("%c",ch);
 }
getch();
}

Video from www.c4learn.com : Step by Step Debugging

C _dos_getdate() function : C Reference

Gets DOS system date in C Programming :

void _dos_getdate(struct dosdate_t *datep);

dosdate_t Structure and Structure Members :

struct dosdate_t {
   unsigned char day;        /* 1--31 */
   unsigned char month;      /* 1--12 */
   unsigned int  year;       /* 1980--2099 */
   unsigned char dayofweek;  /* 0--6; 0 = Sunday */
 };
  • This structure is used by _dos_getdate() and _dos_setdate() function.
  • _dos_getdate fills in the dosdate_t structure *datep with the system’s current date.

C Program to Get/print System Day,Month and year :

#include <dos.h>
#include <stdio.h>
int main(void)
{
  struct dosdate_t d;
  _dos_getdate(&d);
  printf("The current year is: %d\n", d.year);
  printf("The current day is: %d\n", d.day);
  printf("The current month is: %d\n", d.month);
  return 0;
}

Output :

The current year is: 2012
The current day is: 18
The current month is: 1