Combining two text files into third one and keeping track of data - c

I've run into a problem solution to which I can't find.
I'm combining two text files into a third one and I want to keep track of the data I'm moving. So far, the code does one thing and absolutely ignores other.
Here is the code:
// enable standard c i/o functions
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Open two files to be merged
FILE *fp1 = fopen("test1.txt", "r");
FILE *fp2 = fopen("test2.txt", "r");
// Open file to store the result
FILE *fp3 = fopen("results.txt", "w+");
char c;
int count2ch = 0; // count meter for characters
int count1ch = 0; // count meter for characters
int totalch = 0; // holds number of total ammount of characters
int count1wd = 0; // count meter for words
int count2wd = 0; // count meter for words
int totalWD = 0;// holds total ammount of words
// Check files
if (fp1 == NULL || fp2 == NULL || fp3 == NULL)
{
puts("Could not open file");
exit(0);
}
// COUNTING CHARACTERS
// count characters file one
while (1)
{
c = fgetc(fp1);
if (c == EOF)
break;
count1ch++;
}
// count characters file two
while (1)
{
c = fgetc(fp2);
if (c == EOF)
break;
count2ch++;
}
//MERGING FILES
// Copy contents of first file to file3.txt
while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
// Copy contents of second file to file3.txt
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
// COUNTING WORDS
//count words file one
while ((c = fgetc(fp1)) != EOF)
{
if (c == ' ')
count1wd++;
}
//count words file two
while ((c = fgetc(fp2)) != EOF)
{
if (c == ' ')
count2wd++;
}
// count total ammount of words
totalWD = count1wd + count2wd;
// count total ammount of characters
totalch = count1ch + count2ch;
printf("Merged file1.txt and file2.txt into file3.txt \n");
printf("Total number of characters moved: %d\n", totalch);
printf("The ammount of chars in your first file is : %d\n", count1ch);
printf("The ammount of chars in your second file is : %d\n", count2ch);
printf("Total number of words moved: %d\n", totalWD);
printf("The ammount of words in your fist file is : %d\n", count1wd);
printf("The ammount of words in your second file is : %d\n", count2wd);
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
Now, it just combines two files into the third one and that's it. If I move the counting words or characters section above the merging section, the code will do whatever comes first.

Here's your code refined. The only differences are simplified variable names, the print statements moved to a function, and most importantly, the addition of the rewind() function to rewind your file pointers after use. The formatting is also my style, so if you want to change that then feel free.
#include <stdio.h>
#include <stdlib.h>
void printCtrs(int, int, int, int, int, int);
void printCtrs(int ttlCh, int c1ch, int c2ch, int ttlWD, int c1wd, int c2wd){
printf("Merged file1.txt and file2.txt into file3.txt \n");
printf("Total number of characters moved: %d\n", ttlCh);
printf("The ammount of chars in your first file is : %d\n", c1ch);
printf("The ammount of chars in your second file is : %d\n", c2ch);
printf("Total number of words moved: %d\n", ttlWD);
printf("The ammount of words in your fist file is : %d\n", c1wd);
printf("The ammount of words in your second file is : %d\n", c2wd);
}
int main(){
// Open files for reading/writing
FILE *fp1, *fp2, *fp3;
fp1 = fopen("test1.txt", "r");
fp2 = fopen("test2.txt", "r");
fp3 = fopen("results.txt", "w+");
// Declaring counters
char c;
int ttlCh = 0, c1ch = 0, c2ch = 0,
ttlWD = 0, c1wd = 0, c2wd = 0;
// If any files fail to open, abort
if (fp1 == NULL){
puts("Could not open file fp1");
exit(0);
}
if (fp2 == NULL){
puts("Could not open file fp2");
exit(0);
}
if (fp3 == NULL){
puts("Could not open file fp3");
exit(0);
}
// Read through files 1 and 2 and count characters
while (c = fgetc(fp1) != EOF){ c1ch++; }
rewind(fp1); // Reset file pointer 1 to start of file
while (c = fgetc(fp2) != EOF){ c2ch++; }
rewind(fp2); // Reset file pointer 2 to start of file
// Write file 1 and 2 to 3
while ((c = fgetc(fp1)) != EOF){ fprintf(fp3, "%c", c); }
while ((c = fgetc(fp2)) != EOF){ fprintf(fp3, "%c", c); }
// Count total words in 1 and 2
while ((c = fgetc(fp1)) != EOF){
if (c == ' '){ c1wd++; }
}
while ((c = fgetc(fp2)) != EOF){
if (c == ' '){ c2wd++; }
}
ttlWD = c1wd + c2wd;
ttlCh = c1ch + c2ch;
// Print counters
printCtrs(ttlCh, c1ch, c2ch, ttlWD, c1wd, c2wd);
// Close all files after use
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}

Related

How to read a file with numbers on each line in C?

I'm trying to read a file that contains 10 numbers then adding them to an array so I can sort them later on but I'm having trouble reading them in. Not sure why this isn't working for me, can someone explain what is wrong? There's only a number on each lines.
10.05
11.01
9.03
double nums[10] = {0};
int count;
if ((fptr = fopen("filename", "r")) == NULL){
printf("Error opening file.\n");
}
while ((c = getc(fptr)) != EOF){
if (c != '\n'){
nums[count] = (double)c;
count = count + 1;
}
}
fclose(fptr);
What is wrong:
You are storing only one character.
You are updating count each times on non-newline characters while updating should be on newline characters.
count is used without being initialized.
Casting to double is not for this usage.
Possible fix:
int c;
FILE* fptr;
char line[1024]; // add line buffer and size tracking
int lineCount = 0;
double nums[10] = {0};
int count = 0; // initialize count
if ((fptr = fopen("filename", "r")) == NULL){
printf("Error opening file.\n");
} else { // avoid using NULL to read file
while ((c = getc(fptr)) != EOF){
if (c == '\n'){ // update nums on newline character
line[lineCount] = '\0'; // don't forget to terminate the string
nums[count] = atof(line); // atof() from stdlib.h is useful to convert string to number
count = count + 1;
lineCount = 0; // start to read next line
} else { // read line contents
line[lineCount] = (char)c;
lineCount = lineCount + 1;
}
}
fclose(fptr);
}
Here I go
#include <stdio.h>
#include <stdlib.h>
int main()
{
double values[10];
int count;
FILE *f = fopen("filename", "r");
if (f == NULL)| {
fprintf(stderr, "Some error message");
return EXIT_FAILURE; // We cannot go any further - file is dead
}
// This is basic - you could overcome error problems
// When able to read (including white space) we carry on until the array is full
// This is an area for improvement - error checking etc.
for (count = 0; count < 10 && fscanf(f, " %lf", &values[count]) != 1; count ++);
fclose(f);
return EXIT_SUCCESS;
}

How do I count the number of characters in a file?

I have copied the contents of a file to another file and I am trying to get the line, word, and character count. The code I have right now displays the number of lines and words in the file content. Now I need to display the character count but I am unsure of how to do that. I am guessing a for loop? But I am not sure.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define MAX_WORD_LEN 100
#define MAX_LINE_LEN 1000
#define ipsumFile "Lorem ipsum.txt"
#define ipsumCopy "Lorem ipsum_COPY.txt"
int wordCount(FILE *fp);
int charCount(FILE *fp);
int sendContentTo(FILE *fp, FILE *out);
int getWordAt(FILE *fp, int pos, char *word);
int appendToFile(char *fileName, char *newText);
int main(void)
{
FILE *fp, *fp2; //"file pointer"
int ch; //place to store each character as read
//open Lorem ipsum.txt for read
if ((fp = fopen(ipsumFile, "r")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumFile);
exit(EXIT_FAILURE);
}
//open Lorem ipsumCopy for writing
if ((fp2 = fopen(ipsumCopy, "w+")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumCopy);
exit(EXIT_FAILURE);
}
//print out and count all words in Lorem ipsum.txt
int numOfWords = wordCount(fp);
//print out and count all lines in Lorem ipsum.txt
int numOfLines = sendContentTo(fp, stdout);
//copy the content of Lorem ipsum.txt into a new file (ipsumCopy)
numOfLines = sendContentTo(fp, fp2);
fclose(ipsumFile);
fclose(ipsumCopy);
// close Lorem ipsum.txt
if (fclose(fp) != 0)
fprintf(stderr, "Error closing file\n");
if (fclose(fp2) != 0)
fprintf(stderr, "Error closing copy\n");
return 0;
}
int sendContentTo(FILE *in, FILE *out)
{
fprintf(stdout, "Performing file copy...\n\n");
//start at the beginning of the file
rewind(in);
// array to hold one line of text up to 1000 characters
char line[MAX_LINE_LEN];
int lineCount = 0;
// read one line at a time from our input file
while (fgets(line, MAX_LINE_LEN, in) != NULL)
{
//send line we just read to output.
fprintf(out, "%s", line);
//count the lines
lineCount++;
}
fprintf(stdout, "\nFinished line count.\n");
fprintf(stdout, "Count is: %d.\n\n", lineCount);
// Return how many text lines
// we've processed from input file.
return lineCount;
}
// Read content from file one character at a time.
// Returns number of total characters read from the file.
int charCount(FILE *fp)
{
fprintf(stdout, "Performing char count...\n\n");
rewind(fp);
int charCount = 0;
char ch;
//print out each character, and return the
// number of characters in the file.
fprintf(stdout, "\nFinished character count. \n");
fprintf(stdout, "Count is: %d. \n\n", charCount);
return charCount;
}
// Read content from file one word at a time.
// Returns number of total words read from the file.
int wordCount(FILE *fp)
{
fprintf(stdout, "Performing word count...\n\n");
rewind(fp);
char word[MAX_WORD_LEN];
int wordCount = 0;
while (fscanf(fp, "%s", word) == 1)
{
// Send entire word string
// we just read to console
puts(word);
//count the word
wordCount++;
}
fprintf(stdout, "\nFinished word count.\n");
fprintf(stdout, "Count is: %d.\n\n", wordCount);
return wordCount;
}
You don't need to write different function for counting the number of lines, words, and characters in a file. You can do it in a single parsing of file character by character and while parsing, in order to copy the content of file to another file, you can write the characters to another file. You can do:
#include <stdio.h>
#include <stdlib.h>
int count_and_copy(const char * ipsumFile, const char * ipsumCopy)
{
unsigned int cCount = 0, wCount = 0, lCount = 0;
int incr_word_count = 0, c;
FILE *fp, *fp2;
if ((fp = fopen(ipsumFile, "r")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumFile);
exit(EXIT_FAILURE);
}
if ((fp2 = fopen(ipsumCopy, "w+")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumCopy);
exit(EXIT_FAILURE);
}
while((c = fgetc(fp)) != EOF)
{
fputc(c, fp2); // write character c to the copy file
cCount++; // character count
if(c == '\n') lCount++; // line count
if (c == ' ' || c == '\n' || c == '\t')
incr_word_count = 0;
else if (incr_word_count == 0) {
incr_word_count = 1;
wCount++; // word count
}
}
fclose (fp);
fclose (fp2);
printf ("Number of lines : %u\n", lCount);
printf ("Number of words : %u\n", wCount);
printf ("Number of characters : %u\n", cCount);
return 0;
}
int main()
{
/* Assuming, you want to count number of lines, words
* and characters of file1 and copy the contents of file1
* to file2.
*/
count_and_copy("file1", "file2");
return 0;
}
I suppose that the following approach will work:
void *cw(const char *fname)
{
FILE *f = fopen(fname, "r");
if (f == NULL) {
fprintf(stderr, "fopen(%s): %s\n", fname, strerror(errno));
exit(EXIT_FAILURE);
}
int bc = 0; /* bytes counter */
int wc = 0 ; /* words counter */
int nlc = 0; /* new lines counter */
const int in_word_state = 0;
const int out_word_state = 1;
int state = out_word_state;
int c = 0;
for (;;) {
c = fgetc(f);
if (ferror(f) != 0) {
perror("fgetc");
goto error;
}
if (feof(f))
break;
if (c == '\n')
nlc++;
if (c == ' ' || c == '\t' || c == '\n')
state = out_word_state;
if (state == out_word_state) {
state = in_word_state;
wc++;
}
bc++;
}
if (fclose(f) == EOF) {
perror("fclose");
goto error;
}
printf("w: %d, c: %d, l:%d\n", wc, bc, nlc);
error:
if (f != NULL) {
if (fclose(f) == EOF) {
perror("fclose");
}
}
exit(EXIT_FAILURE);
}

A C program to read in two files and display their statistics on screen

I need to make a program that prompts the user for the name of two text files which will be read in and displayed on screen followed by their statistics, such as number of characters, words and lines. I've managed to get it all working apart from the statistics part. They don't seem to be counting up and I think it's something to do with the while statements that I've used. Any help would be great :)
code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main() {
// declaring variables
FILE *fp;
int charcount = 0, wordcount = 0, linecount = 0;
int character;
char first[50];
char second[50];
char ch[200];
// asking the user for the file names and scanning the names they enter as txt files
printf(" Enter the first file name: ");
scanf("%s", first);
strcat(first, ".txt");
printf(" Enter the second file name: ");
scanf("%s", second);
strcat(second, ".txt");
// opening the file stream
fp = fopen(first, "r");
// if the file cannot be reached, display error
if (fp == NULL) {
printf("File cannot be opened: %s\n", first);
return 0;
}
// reading and printing the file into the program
printf("\n---FIRST FILE---\n");
while (!feof(fp)) {
fgets(ch, 200, fp);
puts(ch);
}
// counting the characters, words and lines until the program is finished
while ((character = getc(fp)) != EOF) {
if (character == '-')
{
charcount++;
}
if (character == ' ')
{
wordcount++;
}
if (character == '\n')
{
linecount++;
}
}
// closing the stream
fclose(fp);
// printing the number of characters, words and lines
printf("\n Characters: %d \n Words: %d\n Lines: %d\n\n\n", charcount, wordcount, linecount);
//---------SECOND FILE----------//
// opening the stream
fp = fopen(second, "r");
// reading and printing the file into the program
printf("\n---SECOND FILE---\n");
while (!feof(fp)) {
fgets(ch, 200, fp);
puts(ch);
}
// counting the characters, words and lines until the program is finished
while ((character = getc(fp)) != EOF) {
if (character == '-')
{
charcount++;
}
if (character == ' ')
{
wordcount++;
}
if (character == '\n')
{
linecount++;
}
}
// closing the stream
fclose(fp);
// printing the number of characters, words and lines
printf("\n Characters: %d \n Words: %d\n Lines: %d\n\n", charcount, wordcount, linecount);
}
Imagine that you're using one of those text editors to open your file and moving the caret/cursor is the only way to navigate. Your first goal is to navigate through the whole content and display it. That's what the loop below does:
while(!feof(fp)){
fgets(ch, 200, fp);
puts(ch);
}
The !feof(fp) moved the cursor to the end of the file so you could read it all.
If you have to count chars then you need to navigate back to somewhere in your file. Since you want statistics from the whole txt, then you could simply use rewind(fp) or fseek(fp, 0, SEEK_SET) before your second loop to move the cursor back to the begin.
I recommed using fseek() because it will clear the end of file indicator.
Take a closer look here.
I finally got it to work, if anyone is interested the final code is here:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main() {
// declaring variables
FILE *fp;
int charcount = 0, wordcount = 0, linecount = 1;
int charcount2 = 0, wordcount2 = 0, linecount2 = 1;
int character;
char first[50];
char second[50];
char ch[200];
// asking the user for the file names and scanning the names they enter as txt files
printf(" Enter the first file name: ");
scanf("%s", first);
strcat(first, ".txt");
printf(" Enter the second file name: ");
scanf("%s", second);
strcat(second, ".txt");
// opening the file stream
fp = fopen(first, "r");
// if the file cannot be reached, display error
if (fp == NULL) {
printf("File cannot be opened: %s\n", first);
return 0;
}
// reading and printing the file into the program
printf("\n---FIRST FILE---\n");
while (!feof(fp)) {
fgets(ch, 200, fp);
fputs(ch, stdout);
}
// counting the characters, words and lines until the program is finished
fseek(fp, 0, SEEK_SET);
while ((character = fgetc(fp)) != EOF) {
if (character == EOF)
break;
{
charcount++;
}
if (character == ' ' || character == '.')
{
wordcount++;
}
if (character == '\n')
{
linecount++;
}
}
// closing the stream
fclose(fp);
// printing the number of characters, words and lines
printf("\n Characters: %d \n Words: %d\n Lines: %d\n\n\n", charcount, wordcount, linecount);
//---------SECOND FILE----------//
// opening the stream
fp = fopen(second, "r");
// reading and printing the file into the program
printf("\n---SECOND FILE---\n");
while (!feof(fp)) {
fgets(ch, 200, fp);
fputs(ch, stdout);
}
// counting the characters, words and lines until the program is finished
fseek(fp, 0, SEEK_SET);
while ((character = getc(fp)) != EOF) {
if (character == EOF)
break;
{
charcount2++;
}
if (character == ' ' || character == '.')
{
wordcount2++;
}
if (character == '\n')
{
linecount2++;
}
}
// closing the stream
fclose(fp);
// printing the number of characters, words and lines
printf("\n Characters: %d \n Words: %d\n Lines: %d\n\n", charcount2, wordcount2, linecount2);
}
counting sample
#include <stdio.h>
#include <ctype.h>
typedef struct statistics {
size_t charcount, wordcount, linecount;
} Statistics;
Statistics count_cwl(FILE *fp){
size_t c = 0, w = 0, l = 0;
int ch;
char prev = ' ';
while((ch = getc(fp)) != EOF){
++c;
if(isspace(prev) && !isspace(ch)){
++w;//need to delete punctuation marks ?
}
if(ch == '\n'){
++l;
}
prev = ch;
}
if(prev != '\n')//There is no newline at the end of the file
++l;
return (Statistics){ c, w, l};
}
int main(void) {
char filename[50] = "test.c";
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("File cannot be opened: %s\n", filename);
return -1;
}
Statistics stat = count_cwl(fp);
fclose(fp);
printf("\nCharacters: %zu\nWords: %zu\nLines: %zu\n", stat.charcount, stat.wordcount, stat.linecount);
}

C program to ask for two separate files then displays number of characters, lines and words

I am writing a program to do this but have error messages. I have changed the fopen-s line to what it is now but this message appears after entering the two file names?
error message
here are no error messages that come up in visual studio but not sure if this is not the problem.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
//setting names of ints and chars.
FILE *file_in;
int wordcount, linecount, charcount;
char letter;
char filename1[50];
char filename2[50];
//setting all counts to 0.
wordcount = 0;
linecount = 0;
charcount = 0;
//Gets the user to enter name of file, then puts it in string.
printf("\n Enter first text document\n");
gets_s(filename1);
printf("\n Enter second text document\n");
gets_s(filename2);
//opens then reads the first file.
fopen_s(&file_in, filename1, "r");
// counts the number of words, then lines, then letters in doc 1.
while ((letter = getc(file_in)) != EOF);
{
if (isspace(letter) && !isspace(getchar()))
{
wordcount++;
}
if (letter == '\n');
{
linecount++;
}
if (letter == '-')
{
charcount++;
}
}
//opens then reads the second file.
fopen_s(&file_in, filename2, "r");
// counts the number of words, then lines, then letters in doc 2.
while ((letter = getc(file_in)) != EOF);
{
if (isspace(letter) && !isspace(getchar()))
{
wordcount++;
}
if (letter == '\n');
{
linecount++;
}
if (letter == '-')
{
charcount++;
}
}
//displays the total on screen.
printf_s("Words:", wordcount, "\n");
printf_s("Letters", charcount, "\n");
printf_s("Lines", linecount, "\n")
}
fopen_s takes 3 arguments. First is pointer, to which you want to assign the file, second is filename and third is how you want to acces file ("r", "w", etc)
A few things I found to change here... This code worked for me:
#include "stdio.h"
#include "stdlib.h"
#include "ctype.h"
int main(int argc, char *argv[])
{
//setting names of ints and chars.
FILE *file_in;
int wordcount, linecount, charcount;
int letter;
char filename1[50];
char filename2[50];
//setting all counts to 0.
wordcount = 0;
linecount = 0;
charcount = 0;
printf("Enter first text document: ");
fgets(filename1, 50, stdin);
ch = filename1;
while(*ch != '\n')
ch++;
*ch = '\0';
printf("Enter second text document: ");
fgets(filename2, 50, stdin);
ch = filename2;
while(*ch != '\n')
ch++;
*ch = '\0';
//opens then reads the first file.
file_in = fopen(filename1, "r");
// counts the number of words, then lines, then letters in doc 1.
while((letter = fgetc(file_in)) != EOF)
{
if (letter == ' ')
{
wordcount++;
}
else if (letter == '\n')
{
linecount++;
}
else
{
charcount++;
}
}
//displays the total on screen.
printf("File 1...\n");
printf("Words: %d\n", wordcount);
printf("Letters: %d\n", charcount);
printf("Lines: %d\n", linecount);
//opens then reads the second file.
file_in = fopen(filename2, "r");
//reset counts
wordcount = 0;
linecount = 0;
charcount = 0;
// counts the number of words, then lines, then letters in doc 2.
while((letter = fgetc(file_in)) != EOF)
{
if (letter == ' ')
{
wordcount++;
}
else if (letter == '\n')
{
linecount++;
}
else
{
charcount++;
}
}
//displays the total on screen.
printf("File 2...\n");
printf("Words: %d\n", wordcount);
printf("Letters: %d\n", charcount);
printf("Lines: %d\n", linecount);
}

C Programming- How to delete a line containing a specific word from file?

I have created a stock inventory program for a jewelry store.
However, I cannot seem to figure out how to search for a specific word in a file containing the items (in a table form) and delete the entire line which the word was on.
For example, I can delete earring from the list but not the quantity as well which would be a few spaces away on the same line.
#include <stdio.h>
int main() {
FILE *fp1, *fp2;
//consider 40 character string to store filename
char filename[40];
char c;
int del_line, temp = 1;
//asks user for file name
printf("Enter file name: ");
//receives file name from user and stores in 'filename'
scanf("%s", filename);
//open file in read mode
fp1 = fopen(filename, "r");
c = getc(fp1);
//until the last character of file is obtained
while (c != EOF) {
printf("%c", c);
//print current character and read next character
c = getc(fp1);
}
//rewind
rewind(fp1);
printf(" \n Enter line number of the line to be deleted:");
//accept number from user.
scanf("%d", &del_line);
//open new file in write mode
fp2 = fopen("copy.c", "w");
c = getc(fp1);
while (c != EOF) {
c = getc(fp1);
if (c == '\n')
temp++;
//except the line to be deleted
if (temp != del_line) {
//copy all lines in file copy.c
putc(c, fp2);
}
}
//close both the files.
fclose(fp1);
fclose(fp2);
//remove original file
remove(filename);
//rename the file copy.c to original name
rename("copy.c", filename);
printf("\n The contents of file after being modified are as follows:\n");
fp1 = fopen(filename, "r");
c = getc(fp1);
while (c != EOF) {
printf("%c", c);
c = getc(fp1);
}
fclose(fp1);
return 0;
}
Your code has several issues:
You read the filename with an unprotected call to scanf, if the name typed by the user exceeds 39 characters, you invoke undefined behavior. Make the buffer larger as filenames tend to be long nowadays and protect the format this way:
char filename[256];
if (scanf("%255s", filename) != 1) {
/* end of file reached, deal with this error */
...
}
Your method for reading a file byte by byte is incorrect: c should be defined as an int otherwise you cannot reliably detect EOF. The standard idiom for this is:
int c;
//until the last character of file is obtained
while ((c = getc(fp1)) != EOF) {
//print current character and read next character
putchar(c);
}
In the copy phase, you drop the first character of the file.
You ignore errors. Not only do you invoke undefined behavior, you may actually erase the file after failing to copy its contents.
You ask for a line number from the user, but you do not show the line numbers in the echo phase. Doing so would help.
Here is a improved version:
#include <stdio.h>
int main(void) {
FILE *fp1, *fp2;
//consider 255 character string to store filename
char filename[256];
int c, last, del_line, lineno;
//asks user for file name
printf("Enter file name: ");
//receives file name from user and stores in 'filename'
if (scanf("%255s", filename) != 1) {
perror("missing filename");
return 1;
}
//open file in read mode
fp1 = fopen(filename, "r");
if (fp1 == NULL) {
perror("cannot open file");
return 1;
}
//until the last character of file is obtained
last = '\n';
lineno = 0;
while ((c = getc(fp1)) != EOF) {
if (last == '\n') {
printf("%4d: ", ++lineno);
}
//print current character and read next character
putchar(c);
last = c;
}
rewind(fp1);
printf("\nEnter line number of the line to be deleted: ");
//accept number from user.
if (scanf("%d", &del_line) != 1) {
perror("missing line number");
return 1;
}
if (del_line < 1 || del_line > lineno) {
printf("no such line: %d\n", del_line);
return 1;
}
//open new file in write mode
fp2 = fopen("copy.c", "w");
if (fp2 == NULL) {
perror("cannot open copy.c");
return 1;
}
lineno = 1;
while ((c = getc(fp1)) != EOF) {
//except the line to be deleted
if (lineno != del_line) {
//copy all lines in file copy.c
putc(c, fp2);
}
if (c == '\n')
lineno++;
}
//close both files.
fclose(fp1);
if (fclose(fp2)) {
perror("write error to copy.c");
return 1;
}
// remove original file (unsafe)
// uncomment this if your system does not allow rename
// to overwrite existing files
// if (remove(filename)) {
// perror("cannot remove source file");
// return 1;
// }
//rename the file copy.c to original name
if (rename("copy.c", filename)) {
perror("cannot rename file");
return 1;
}
printf("\nThe contents of file after being modified are as follows:\n");
fp1 = fopen(filename, "r");
if (fp1 == NULL) {
perror("cannot re-open modified file");
return 1;
}
while ((c = getc(fp1)) != EOF) {
putchar(c);
}
fclose(fp1);
return 0;
}

Resources