Difference between fprintf, printf and sprintf?

Printf    –   writes output to the standard output stream(stdout).

Syntax:
int printf(const char* str, …);

Example:
// Example program to demonstrate printf()
#include<stdio.h>
int main()
{
printf(“hello Innovation Begins Here\n”);
return 0;
}

O/P: hello Innovation Begins Here
Man page: printf(3): formatted output conversion

Sprintf   –   writes output to a buffer that you allocate(char*).

Syntax:
int sprintf(char *str, const char *string,…);
String print function it is stead of printing on console store it on char buffer which are specified in sprint.

Example:
// Example program to demonstrate sprintf()
#include<stdio.h>
int main()
{
char buffer[10];
int a = 1, b = 2, c;
c = a + b;
sprintf(buffer, “Sum of %d and %d is %d”, a, b, c);
// The string “sum of 1 and 2 is 3” is stored
// into buffer instead of printing on stdout
printf(“%s”, buffer);
return 0;
}
O/P: Sum of 10 and 20 is 30
Man page: sprintf(3): formatted output conversion

Fprintf  –  writes output to a file handle (FILE *).

Syntax:
int fprintf(FILE *fptr, const char *str, …);

Example:
#include<stdio.h>
int main()
{
int i, n=1;
char str[50];
//open file sample.txt in write mode
FILE *fptr = fopen(“sample.txt”, “w”);
if (fptr == NULL)
{
printf(“Could not open file”);
return 0;
}
for (i=0; i<n; i++)
{
puts(“Enter a name”);
gets(str);
fprintf(fptr,”%d.%s\n”, i, str);
}
fclose(fptr);
return 0;
}

O/P: Input  from your keyboard Innovation Begins Here
Output: sample.txt file now having output as
Innovation Begins Here
Man page: fprintf(3): formatted output conversion

Follow Innovation Begins Here on Twitter,Facebook , Google+ &Linkdin.

 

Advertisements

What are the valid signatures for C’s main() function – int main() or void main() ?

Neither main() or void main() are standard C. The former is allowed as it has an implicit intreturn value, making it the same as int main(). The purpose of main’s return value is to return an exit status to the operating system.

The current C standard C11 valid signatures for main are:

int main(void)

int main(int argc, char **argv)

The form you’re using: int main() is an old style declaration that indicates main takes an unspecified number of arguments. Don’t use it – choose one of those above.

Exit Status:

The exit status or return code of a process in computer programming is a small number passed from a child process (or callee) to a parent process (or caller) when it has finished executing a specific procedure or delegated task. In DOS, this may be referred to as an errorlevel.

The C programming language allows programs exiting or returning from the main function to signal success or failure by returning an integer, or returning the macros EXIT_SUCCESS and EXIT_FAILURE. On Unix-like systems these are equal to 0 and 1 respectively.

Follow Innovation Begins Here on Twitter,Facebook , Google+ &Linkdin.