I'm creating a program to merge 2 text files in C (these 2 files must have already exist in the system)
#include <stdio.h>
#include <stdlib.h>
int main() {
char c;
char n1[10], n2[10];
FILE *f1, *f2, *f3;
printf("Please enter name of file input 1: ");
scanf("%s", n1);
f1 = fopen(n1, "r");
printf("Please enter name of file input 2: ");
scanf("%s", n2);
f2 = fopen(n2, "r");
f3 = fopen("question_bank.txt", "w");
if (f1 == NULL || f2 == NULL || f3 == NULL) {
printf("Error");
return 1;
}
while ((c = fgetc(f1)) != EOF) {
fputc(c, f3);
}
while ((c = fgetc(f2)) != EOF) {
fputc(c, f3);
}
fclose(f1);
fclose(f2);
fclose(f3);
return 0;
}
Everything is pretty ok but I realise that I need to enter the second file's content on a new line, not at the end of the first file's text. What change should I apply to my code?
If the first file does not end with a newline character, you should output one before copying the contents of the second file.
Note also that c must be defined as int.
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <string.h>
int main() {
int c, last = 0;
char n1[80], n2[80];
FILE *f1, *f2, *f3;
printf("Please enter name of file input 1: ");
if (scanf("%79s", n1) != 1)
return 1;
printf("Please enter name of file input 2: ");
if (scanf("%79s", n2) != 1)
return 1;
f1 = fopen(n1, "r");
if (f1 == NULL) {
fprintf(stderr, "Cannot open %s: %s\n", n1, strerror(errno));
return 1;
}
f2 = fopen(n2, "r");
if (f2 == NULL) {
fprintf(stderr, "Cannot open %s: %s\n", n2, strerror(errno));
return 1;
}
f3 = fopen("question_bank.txt", "w");
if (f3 == NULL) {
fprintf(stderr, "Cannot open %s: %s\n", "question_bank.txt", strerror(errno));
return 1;
}
while ((c = fgetc(f1)) != EOF) {
last = c;
fputc(c, f3);
}
if (last != '\n') {
fputc('\n', f3);
}
while ((c = fgetc(f2)) != EOF) {
fputc(c, f3);
}
fclose(f1);
fclose(f2);
fclose(f3);
return 0;
}
Related
I was trying to encrypt a file from a header file and every time I run the program, it deletes the information in the file AccountInformation.txt. Is there any reason why it is deleting the information from AccountInformation.txt and how can I fix my code?
Any help will be great, thank you.
The c code is bellow:
#include <stdio.h>
#include <string.h>
#include "Encryption1.h"
// Variable for signup and login
char fname[120], lname[120], username[120], password[120];
int session;
FILE * accountInfoPointer;
// Main Fucntion for sign up and login
int main (void)
{
// Asking user is they want to sign up or login
printf("What would you like to do?\n");
printf("1. Sign u\n");
printf("2. Login\n");
printf("3. Admin login");
scanf("%d", &session);
// signup
switch(session)
{
case 1:
// Retreiving all of the user's data
printf("What is your FIRST name?\n");
scanf(" %s", fname);
printf("What is your LAST name?\n");
scanf(" %s", lname);
printf("Please enter a username?\n");
scanf(" %s", username);
printf("Create a password\n");
scanf(" %s", password);
accountInfoPointer = fopen("AccountInformation.txt", "a");
fprintf(accountInfoPointer, "Name: %s %s\nUsername: %s\nPassword: %s\n\n", fname, lname, username, password);
fclose(accountInfoPointer);
goto Encrypt; //goes to calender menu
Encrypt:{
//char Title;{
printf("\n\n\t\t\t\t::::::Encrypt::::::\n");
encrypted1(1);
}
break;
}
}
This is the header file code:
#include<stdio.h>
#include<stdlib.h>
int encrypt(void);
int decrypt(void);
int encrypt_view(void);
int decrypt_view(void);
FILE *fp1, *fp2;
char ch;
void encrypted1(int Encrypt)
{
int choice;
while(1)
{
printf("Select One of the Following:\n");
printf("\n1. Encrypt\n");
printf("2. Decrypt\n");
printf("3. View The Encypted File\n");
printf("4. View The Decrypted File\n");
printf("5. Exit\n");
printf("\nEnter Your Choice:\t");
scanf("%d", &choice);
switch(choice)
{
case 1: encrypt();
break;
case 2: decrypt();
break;
case 3: encrypt_view();
break;
case 4: decrypt_view();
break;
case 5: exit(1);
}
}
printf("\n");
// return 0;
}
int encrypt()
{
printf("\n");
fp1 = fopen("AccountInformation.txt","r");
if(fp1 == NULL)
{
printf("Source File Could Not Be Found\n");
}
fp2 = fopen("AccountInformation.txt","w");
if(fp2 == NULL)
{
printf("Target File Could Not Be Found\n");
}
while(1)
{
ch = fgetc(fp1);
if(ch == EOF)
{
printf("\nEnd Of File\n");
break;
}
else
{
ch = ch - (8 * 5 - 3);
fputc(ch, fp2);
}
}
fclose(fp1);
fclose(fp2);
printf("\n");
//return 0;
}
int decrypt()
{
printf("\n");
fp1 = fopen("AccountInformation.txt","r");
if(fp1 == NULL)
{
printf("Source File Could Not Be Found\n");
}
fp2 = fopen("AccountInformation.txt","w");
if(fp2 == NULL)
{
printf("Target File Could Not Be Found\n");
}
while(1)
{
ch = fgetc(fp1);
if(ch == EOF)
{
printf("\nEnd Of File\n");
break;
}
else
{
ch = ch + (8 * 5 - 3);
fputc(ch, fp2);
}
}
fclose(fp1);
fclose(fp2);
printf("\n");
//return 0;
}
int encrypt_view()
{
printf("\n");
fp1 = fopen("AccountInformation.txt","r");
if(fp1 == NULL)
{
printf("No File Found\n");
exit(1);
}
else
{
while(1)
{
ch = fgetc(fp1);
if(ch == EOF)
{
break;
}
else
{
printf("%c", ch);
}
}
printf("\n");
fclose(fp1);
}
printf("\n");
//return 0;
}
int decrypt_view()
{
printf("\n");
fp1 = fopen("AccountInformation.txt","r");
if(fp1 == NULL)
{
printf("No File Found\n");
exit(1);
}
else
{
while(1)
{
ch = fgetc(fp1);
if(ch == EOF)
{
break;
}
else
{
printf("%c", ch);
}
}
printf("\n");
fclose(fp1);
}
// return 0;
printf("\n");
}
fp1 = fopen("AccountInformation.txt","r");
if(fp1 == NULL)
{
printf("Source File Could Not Be Found\n");
}
fp2 = fopen("AccountInformation.txt","w");
if(fp2 == NULL)
{
printf("Target File Could Not Be Found\n");
}
I cringe at this, but the idea should work on unix derivatives. You're clobbering your data because you should have used "r+" but you used "w". The + turns on both read and write, but w+ is going to truncate. You don't want a. Unless you're writing a log file, you don't want a so don't try it here.
At least this problem:
Unable to distinguish all input from fgetc() properly
char, as 8-bit, can encode 256 combinations. int fgetc() returns 257 values: [0-UCHAR_MAX] and EOF.
Code encrypts with ch = ch - (8 * 5 - 3); fputc(ch, fp2); which easily generates a char that collides with EOF on a later read making the file scant.
char ch; // Bad
ch = fgetc(fp1);
if(ch == EOF) // Was ch an EOF or some character?
Use int ch to distinguish the return values from fgetc().
For encryption/decryption, better to open the files in binary mode than text mode. Append a "b".
// fp1 = fopen("AccountInformation.txt","r");
fp1 = fopen("AccountInformation.txt","rb");
Alternative sample code:
int encrypt_view(void) {
printf("\n");
FILE *fp = fopen("AccountInformation.txt", "rb");
if (fp == NULL) {
printf("No File Found\n");
return 1; // Let calling code exit
}
int ch;
while ((ch = fgetc(fp)) != EOF) {
if (ch >= ' ' && ch <= '~') {
printf("%c", ch);
} else {
printf("<%d>", ch);
}
}
printf("\n");
fclose(fp);
return 0;
}
I have written a C program that opens a text file and compares the given string with the string present in the file. I'm trying to print the line number in which the same string occurs, but I am unable to get the proper output: output does not print the correct line number.
I would appreciate any help anyone can offer, Thank you!
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
int num = 0, line_number = 1;
char string[50];
char student[100] = { 0 }, chr;
while (student[0] != '0') {
FILE *in_file = fopen("student.txt", "r");
if (in_file == NULL) {
printf("Error file missing\n");
exit(1);
}
printf("please enter a word \n");
scanf("%s", student);
while (fscanf(in_file, "%s", string) == 1) {
if (chr == '\n') {
if (strstr(string, student) == 0) {
break;
} else
line_number += 1;
}
}
printf("line number is: %d\n", line_number);
fclose(in_file);
}
return 0;
}
You cannot read lines with while (fscanf(in_file, "%s", string), the newlines will be consumed by fscanf() preventing you from counting them.
Here is an alternative using fgets():
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char string[200];
char student[100];
int num = 0, line_number = 1;
FILE *in_file = fopen("student.txt", "r");
if (in_file == NULL) {
printf("Error file missing\n");
exit(1);
}
printf("please enter a word \n");
if (scanf("%s", student) != 1) {
printf("No input\n");
exit(1);
}
while (fgets(string, sizeof string, in_file)) {
if (strstr(string, student)) {
printf("line number is: %d\n", line_number);
}
if (strchr(string, '\n')) {
line_number += 1;
}
fclose(in_file);
}
return 0;
}
here's the code i wrote:
#include <stdio.h>
#include <stdlib.h>
void Print_File(FILE *f)
{
fopen("f", "r");
char s = fgetc(f);
while (s != EOF)
{
printf("%c", s);
s = fgetc(f);
}
fclose(f);
}
int main(void)
{
FILE *ptr = fopen("info.txt", "a");
if(ptr == NULL)
{
printf("Invalid Input\n");
return 1;
}
char *c = malloc(sizeof(char) * 101);
printf("One entry cannot be more than 100 characters long!\n");
printf("Enter your text here - ");
scanf("%[^\n]%*c", c);
fprintf(ptr, "%s\n", c);
fclose(ptr);
Print_File(ptr);
free(c);
}
After Executing the program on command line, when i manually open the file, it is updated alright!
But the file is not printed! Did I write the Print_File() function wrong?
Look at the manual page for fopen(). It takes a file name as first argument, and it returns a FILE *. What you are doing is wrong.
You should change this:
fopen("f", "r");
To this:
FILE *f;
f = fopen("file-name-here", "r");
if (f == NULL) {
puts("Error opening file!");
exit(1);
}
Secondly, passing ptr, which is a closed file, to the function, is useless. Either open it before calling the function (and at that point do not use fopen() inside it) or just declare the function as taking no arguments and open it inside.
Option 1:
void Print_File(FILE *f)
{
// ... use already opened file ...
}
// Then in main:
ptr = fopen("file-name-here", "r");
if (ptr == NULL) {
puts("Error opening file!");
exit(1);
}
Print_File(ptr);
Option 2:
void Print_File(void) // void == takes no arguments
{
FILE *f;
f = fopen("file-name-here", "r");
// ...
}
// Then in main:
Print_File();
Lastly, fgetc() returns an int. You need to use an int variable to hold the result, or you won't be able to distinguish between a valid character and EOF:
int s = fgetc(f);
while (s != EOF)
{
// ...
Complete working example:
#include <stdio.h>
#include <stdlib.h>
void Print_File(FILE *f)
{
int s = fgetc(f);
while (s != EOF)
{
printf("%c", s);
s = fgetc(f);
}
fclose(f);
}
int main(void)
{
FILE *ptr = fopen("info.txt", "a");
if(ptr == NULL) {
printf("Error opening file for writing.\n");
return 1;
}
char *c = malloc(sizeof(char) * 101);
if (c == NULL) {
printf("Error allocating memory.\n");
return 1;
}
printf("One entry cannot be more than 100 characters long!\n");
printf("Enter your text here - ");
scanf("%[^\n]%*c", c);
fprintf(ptr, "%s\n", c);
fclose(ptr);
ptr = fopen("info.txt", "r");
if(ptr == NULL) {
printf("Error opening file for reading.\n");
return 1;
}
Print_File(ptr);
free(c);
return 0;
}
Output:
$ gcc prog.c -o prog
$ ./prog
One entry cannot be more than 100 characters long!
Enter your text here - HELLO WORLD
HELLO WORLD
$ ./prog
One entry cannot be more than 100 characters long!
Enter your text here - HELLO WORLD AGAIN
HELLO WORLD
HELLO WORLD AGAIN
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);
}
The problem: Use a c program to read a MIPS instruction file, output it to a second file (both are command line arguments) which contains the contents of the MIPS file, with line numbers. The second half is supposed to display a cross reference table, which details the identifier, the definition(a number), and the usage of that identifier, by line number, for any identifier used more than once.
Unfortunately, I've run aground, and the program not only doesnt seem to actually print anything, but it doesnt seem to make any files either. This is a bit of a last ditch effort, to see if anyone else can help me out.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*Func line takes in a file, and places a line number at the beginning of every
non blank line */
void line(FILE *input, FILE *output) {
char a, c;
int lineNum = 0;
int startOfLine = 1;
char ch;
fprintf(output, "%d ", ++lineNum);
//copy the contents of the input file into the output file
do {
a = fgetc(input);
fputc(a, output);
c = getc(input);
if(a == '\n' && c != '\n') {
if(lineNum > 9)
fprintf(output, "%d ", ++lineNum);
else
fprintf(output, "%d ", ++lineNum);
}
ungetc(c, input);
} while (a != EOF);
printf("ran line: \n");
}
/* Func cross takes in a file, and finds each identifier, marks its definition, and every
use and returns that in the output file */
void cross(FILE *input, FILE *output) {
FILE *temp = fopen("temp.txt", "a+");
int lineNum = 0;
int startOfLine = 1;
char identifier[20][10];
char a, c, i;
int j, k, p;
int size=0;
int def[20];
int use[20][50];
char tempstr[80];
fprintf(output, "Identifier\tDefinition\t Use\n");
fprintf(temp, "%d ", ++lineNum);
//copy contents of input into a temp file
do {
a = fgetc(input);
fputc(a, temp);
c = getc(input);
if(a == '\n' && c != '\n') {
if(lineNum > 9)
fprintf(temp, "%d ", ++lineNum);
else
fprintf(temp, "%d ", ++lineNum);
}
ungetc(c, input);
} while (a != EOF);
fclose(temp);
fopen("temp.txt", "r");
j=0;
//checks to see if current line has an Identifier and if so saves it to an array
//along with the line number it was defined on
while(fgets(tempstr, 80, temp)) {
if(isalpha(tempstr[4]) || tempstr[4] == '_') {
sscanf(tempstr, "%d %[0-9_A-Z_a-z_]", &def[j], identifier[j]);
j++;
size++;
}
}
fclose(temp);
fopen("temp.txt", "r");
//checks for each identifier, on every line whether or not that identifier is used
while(fgets(tempstr, 80, temp)) {
char *tempNum;
sscanf(tempstr, "%s", tempNum);
int tempN = atoi(tempNum);
int n;
p=0;
for(n=0; n<size; n++) {
if(strstr(tempstr, identifier[n]) && tempN > def[n] && tempstr[4] != '#') {
use[n][p] = tempN;
p++;
}
}
}
//writes the identifier, definition, and uses to the file
for(k=0;k<size;k++) {
fprintf(output, "%s\t\t %d\t\t ", identifier[k], def[k]);
for(p=0; p<50; p++) {
if(use[k][p] != NULL && use[k][p] < lineNum && use[k][p] > def[k])
fprintf(output,"%d ", use[k][p]);
}
fprintf(output, "\n");
}
printf("ran cross: \n");
}
/*Func both returns the file with numbered lines and a cross reference table at the bottom of the file */
void both(FILE *input, FILE *output, char *outputName) {
FILE *lineFile = fopen("line.txt", "a+");
FILE *crossFile = fopen("cross.txt", "a+");
char ch;
line(input, lineFile);
cross(input, crossFile);
while( (ch = fgetc(lineFile)) != EOF)
fputc(ch, output);
fprintf(output, "\n\t\t\tCross Reference Table\n");
while( (ch = fgetc(crossFile)) != EOF)
fputc(ch, output);
fclose(output);
printf("ran both: \n");
}
int main(int argc, char * argv[]) {
FILE *input, *output;
output = fopen(argv[4], "a+");
char outputName[50];
strcpy(outputName, argv[4]);
//Error testing
if(argc > 5)
exit(1);
if(strcmp(argv[2], "-l") != 0 && strcmp(argv[2], "-c") != 0 && strcmp(argv[2], "-b") != 0) {
printf("Incorrect flag syntax... Exiting\n");
exit(1);
}
if((input = fopen(argv[3], "r+")) == NULL) {
printf("Input file could not be opened... Exiting\n");
exit(1);
}
else {
if(strcmp(argv[2], "-l") == 0) {
line(input, output);
}
else if(strcmp(argv[2], "-c") == 0)
cross(input, output);
else {
both(input, output, outputName);
}
}
printf("ran main: \n");
return 0;
}