Write a C program to reverse the first n characters in a file.
(Note: The file name and n are specified on the command line.)
Algorithm:
Step 1: Start Step 2: read the command line arguments Step 3: check if arguments = 3 or not If not print invalid no of arguments Step 4: open source file in read mode Step 5: if NULL pointer, then print file can not be open Step 6: Store no of chars to reverse in k.K = *argv[2] - 48 Step 7: read the item from file stream using fread Step 8: Store chars from last position to initial position in another string(temp) Step 9: print the temp string Step 10: Stop
Program:
#include<stdio.h > #include<conio.h > #include<string.h > #include<process.h > void main(int argc, char *argv[]) { FILE *fs, *fd; char s[20], d[20]; int c = 0, count = 0, n; clrscr(); strcpy(s, argv[1]); n = atoi(argv[2]); fs = fopen(s, "r"); if(s == NULL) printf("\n FILE ERROR"); printf("\n SOURCE FILE :\n"); while(!feof(fs)) { printf("%c", fgetc(fs)); c++; } fclose(fs); fs = fopen(s, "r+"); count = 0; while(count < n) { d[count] = fgetc(fs); count++; } d[count] = '\0'; fseek(fs, 0L, 0); fputs(strrev(d), fs); fclose(fs); fs = fopen(s,"r"); while(!feof(fs)) { printf(“%c”, fgetc(fs)); c++; } fclose(fs); getch(); }
Input & Output:
-
UpdatedOct 21, 2014
-
Views27,077
You May Like
Write a C program to find the roots of a quadratic equation
.
Write a C program to count the lines, words and characters in a given text.
Write a C program to find the sum of individual digits of a positive integer.
Write a C program, which takes two integer operands and one operator from the user, performs the operation and then prints the result. (Consider the operators +,-,*, /, % and use switch statement
)
Write a C program to generate all the prime numbers
between 1 and n, where n is a value supplied by the user.
Write C programs that use both recursive
and non-recursive functions
- To find the
factorial
of a given integer. - To find the
GCD
(greatest common divisor) of two given integers.