This blog is under construction

Friday, 27 April 2012

fprintf example in C

Header file:

     int fprintf(FILE *stream, const char *format, ...);

    Performs formatted output conversion and writes the output to stream.  It gives us the number of characters printed (excludes '\0') as return value.

fprintf function C example:

  int main() {
        char name[100], company[100];
        int age, salary;
        FILE *fp;
        fp = fopen("employee.txt", "w");
        printf("Enter your name:");
        fgets(name, 90, stdin);
        name[strlen(name) - 1] = '\0';
        printf("Enter your desination:");
        fgets(company, 90, stdin);
        company[strlen(company) - 1] = '\0';
        printf("Enter yout age and salary:");
        scanf("%d%d", &age, &salary);
        fprintf(fp, "Employee details:\n");
        fprintf(fp, "Name: %s\nCompany: %s\n", name, company);
        fprintf(fp, "Age: %d\nSalary:%d\n", age, salary);
        return 0;

  jp@jp-VirtualBox:~/cpgms/exp$ ./a.out
  Enter your name: Micheal
  Enter your designation: Engineer
  Enter yout age and salary: 23  10000
  jp@jp-VirtualBox:~/cpgms/exp$ cat employee.txt
  Employee details:
  Name: Micheal
  Company: Engineer
  Age: 23

No comments:

Post a Comment