Only last fprintf() output is written to the file - c

I'm trying to write a program which encrypts a input file and creates an output file after the encryption.
The fprintf does work fine if I write to stdout but when I send the output to a file, only the last fprintf output is written into the file, i.e. if the input file contains 2 lines, the output file contains only the last line encrypted.
Source:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define Max 1024
int menu()
{
printf("To encrypt, input e or E\n");
printf("To decrypt, input d or D\n");
printf("To exit, input any other letter\n");
printf("Please enter your choice and hit return:\n");
return 0;
}
void encrypto(char*str)
{
FILE *ausgabeverschl;
ausgabeverschl=fopen("encrypted.txt","w");
int n=0;
char *p=str ,q[Max];
while(*p)
{
if(islower(*p))
{
if((*p>='a')&&(*p<'x'))
q[n]=toupper(*p + (char)3);
}
else
{
q[n]=*p+(char)3;
}
n++; p++;
}
q[n++]='\0';
fprintf(ausgabeverschl, "%s\n", q); // problem occurs here
fclose(ausgabeverschl);
}
void decrypto(char*str)
{
FILE *ausgabeunverschl;
ausgabeunverschl=fopen("decrypted.txt","w");
int n=0;
char *p=str, q[Max];
while(*p)
{
if(isupper(*p))
{
if((*p>='D')&&(*p<='Z'))
q[n]=tolower(*p - (char)3);
}
else
{
q[n]=*p-(char)3;
}
n++; p++;
}
q[n++]='\0';
fprintf(ausgabeunverschl,"%s\n",q);
fclose(ausgabeunverschl);
}
int main()
{
char einlesestring[Max];
char choice[2];
FILE *ein;
ein=fopen("text.txt","r");
if(ein!=NULL)
{
printf("\nFile found.\n\n");
}
if(ein==NULL)
{
printf("No file found.\n");
return 1;
}
int counter=0;
char stringlaenge[Max];
while (fgets(stringlaenge, Max, ein) != NULL)
{
counter++;
}
printf(„Counted lines: %d\n", counter);
rewind(ein);
menu();
gets(choice);
if((choice[0]=='e')||(choice[0]=='E'))
{
while(fgets(einlesestring, Max, ein)!= NULL)
{
encrypto(einlesestring);
}
}
else if((choice[0]=='d')||(choice[0]=='D'))
{
while(fgets(einlesestring,Max, ein)!=NULL)
{
decrypto(einlesestring);
}
}
fclose(ein);
return 0;}
Thanks for helping!

Related

C program to print line number in which given string exists in a text file

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;
}

Why is my code printing out letter by letter instead of sentence by sentence?

The aim of my code is to read in multiple lines of text from a text file and for each line, print out "palindrome" then the line of text if it's a palindrome and print out "Not palindrome" and the line of text if it's not palindrome.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int palindrome(char str[])
{
int l=0;
int h = strlen(str) -1;
while (h>l)
{
if (str[l++] != str[h--])
{
printf("%s -> Not Palindrome",str);
return;
}
}
printf("%s is palindrome",str);
}
int main()
{
char str[100];
FILE*fptr;
fptr= fopen("Lab12input.txt","r");
if (fptr == NULL)
{
printf("can't open file");
exit(0);
}
while (fscanf(fptr,"%s",str) != EOF)
{
palindrome(str);
printf("\n");
}
fclose(fptr);
return 0;
}
uhh a %s to [fs]?scanf() is a whitespace-delimited word, it breaks at the space character. By "sentence by sentence" you mean "line by line" which is what fgets() does.

Program not giving any output after taking input from user

I was creating on a very basic program in C which takes a word from user as input and searches for how many times it appears in a text file and gives output.
The code is:
#include<stdio.h>
#include<string.h>
int main()
{
char user[20];
char word[20];
int i,pos=0,sum=0;
char c;
c='a';
printf("Enter the word you want to look for\n");
gets(user);
FILE *p;
p=fopen("D:\\trees.txt","r+");
do
{
pos=0;
fscanf(p,"%s",word);
if(c!=EOF)
{
if(strlen(word)==strlen(user))
{
for(i=0;i<strlen(user);i++)
{
if(word[i]==user[i]||word[i]==user[i]+32||word[i]==user[i]-32)
{
}
else
{
pos=1;
break;
}
}
}
else
{
pos=1;
}
if(pos=0)
{
sum++;
}
}
}
while(c!=EOF)
;printf("\nNumber of times %s appears is %d",user,sum);
fclose(p);
}
Now the program takes the input fine, but doesn't give any output.
Looks like this:
What have I done wrong?
Looking at the comments, your code should be something like:
#include<stdio.h>
#include<string.h>
#include <ctype.h>
int main()
{
char user[20];
char word[20];
int n, pos=0, sum=0;
unsigned int i, l;
FILE *p;
do {
printf("Enter the word you want to look for\n");
} while (gets(user)==0);
user[strlen(user)-1]= '\0'; // remove trailing \n
if ((p=fopen("D:\\trees.txt","r+"))==0) {printf("Error opening file\n"); exit(0);}
do
{
pos=0;
n= fscanf(p,"%s",word);
if (n==1)
{
if(strlen(word)==(l=strlen(user)))
{
for(i=0; i<l; i++)
{
if(!(word[i]==user[i]||word[i]==tolower(user[i])||word[i]==toupper(user[i])))
{
pos=1;
break;
}
}
}
else pos=1;
if(pos==0) sum++;
}
}
while(n==1);
printf("\nNumber of times %s appears is %d",user,sum);
fclose(p);
return(1);
}
(with some optimizations and additions)

File does not fprint correctly in C?

So here I have a basic program that will write to a specific line in a file by writing the contents of the file into a temporary file where the new line is written and then the contents of that file is then copied back into the starting file.
(Scores) = File
(Sub) = Temp
#include <stdio.h>
#include <conio.h>
#include <string.h>
void insert(void);
int main()
{
insert();
}
void insert(void)
{
FILE *fp,*fc;
int lineNum;
int count=0;
char ch=0;
int edited=0;
int score=0;
fp=fopen("Test 02 Scores.txt","r");
fc=fopen("Sub.txt","w");
if(fp==NULL||fc==NULL)
{
printf("\nError...cannot open/create files");
exit(1);
}
printf("Enter the score");
scanf("%d",&score);
printf("\nEnter Line Number Which You Want 2 edit: ");
scanf("%d",&lineNum);
while((ch=fgetc(fp))!=EOF)
{
if(ch=='\n')
count++;
if(count==lineNum-1 && edited==0)
{
if(lineNum==1)
{
fprintf(fc,"%d\n",score);
}
else
fprintf(fc,"\n%d\n",score);
edited=1;
while( (ch=fgetc(fp))!=EOF )
{
if(ch=='\n')
break;
}
}
else
fprintf(fc,"%d",ch);
}
fclose(fp);
fclose(fc);
if(edited==1)
{
printf("\nLine has been written successfully.");
char ch;
FILE *fs, *ft;
fs = fopen("Sub.txt", "r");
if( fs == NULL )
{
printf("File is not real");
exit(1);
}
ft = fopen("Test 02 Scores.txt", "w");
if( ft == NULL )
{
fclose(fs);
printf("File is not real\n");
exit(1);
}
while( ( ch = fgetc(fs) ) != EOF )
fputc(ch,ft);
printf("\nFile copied\n");
getch();
fclose(fs);
fclose(ft);
}
else
printf("\nLine Not Found");
}
However, a problem has arisen, I started to write this code for use with strings, but since decided to use number values, whenever I try to copy with the integer values the program will not copy anything right, I Know this may be caused by the char to int but I'd rather have more help in assessing where I should change stuff.
The error is in this line
fprintf(fc,"%d",ch)
%d prints ch as an integer, not as a character, you should instead write
fprintf(fc,"%c",ch)
or use fputc()
There are some small issues with your code, here is a working version. I added comments where I changed things.
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h> // needed for exit()
void insert(void);
int main()
{
insert();
}
// use fgets to read from keyboard, it is simpler.
int readNumber()
{
char buffer[64] = {0};
fgets(buffer, sizeof(buffer), stdin);
return atoi(buffer);
}
void insert(void)
{
FILE *fp = NULL; // prefer one decl per row
FILE *fc = NULL;
int lineNum = 0;
int count=0;
int ch=0; // should be int ch=0;
int edited=0;
int score=0;
// file names
const char src[] = "Test 02 Scores.txt";
const char dest[] = "Sub.txt";
fp=fopen(src,"r");
if(fp==NULL)
{
perror(src); // use perror() instead for better error msg
exit(EXIT_FAILURE); // there are std constants for exit args
}
fc=fopen(dest,"w");
if(fc==NULL)
{
perror(dest);
exit(EXIT_FAILURE);
}
printf("Enter the score: ");
score = readNumber(); // using fgets to avoid lingering \n in buffer
printf("\nEnter Line Number Which You Want 2 edit: ");
lineNum = readNumber();
while((ch=fgetc(fp))!=EOF) // fgetc returns int so ch should be int
{
if(ch=='\n') // better to have {} here too
{
count++;
}
if(count==lineNum-1 && edited==0)
{
if(lineNum==1)
{
fprintf(fc,"%d\n",score);
}
else // better to { } here too
{
fprintf(fc,"\n%d\n",score);
}
edited=1;
// i guess you want to remove old score
while( (ch=fgetc(fp))!=EOF )
{
if(ch=='\n')
{
break;
}
}
}
else // {} for avoiding future pitfall
{
fputc(ch,fc);
}
}
fclose(fp);
fclose(fc);
if(edited==1)
{
puts("\nLine has been written successfully."); // puts() when u can
int ch = 0; // int
FILE *fs = NULL;
FILE *ft = NULL;
fs = fopen(dest, "r");
if( fs == NULL )
{
perror(dest);
exit(EXIT_FAILURE);
}
ft = fopen(src, "w");
if( ft == NULL )
{
perror(src);
exit(EXIT_FAILURE); // at program exit files will close anyway
}
while( ( ch = fgetc(fs) ) != EOF )
{
fputc(ch,ft);
}
fclose(fs);
fclose(ft);
printf("\nFile copied\n");
getch();
}
else
{
printf("\nLine Not Found");
}
}

Store and eliminating garbage values

Everytime I try to run the code it'll print out the contents of the file, however it will print out a garbage value at the end which I don't know how to get rid of. I am supposed to to store the contents of the file into an array, however I am a bit confused on how to do that???
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char filePrinter(char*arr)
int main (int argc, char**argv)
{
char fileArray[150];
if(argc !=2)
{
printf("Invalid Entry. Please Enter name of program followed by input filename\n");
}
filePrinter(fileArray);
return 0;
}
char filePrinter(char*arr)
{
int i;
FILE*file;
i=0;
file=fopen("assests/room.txt","r");
if(file == NULL)
{
printf("Could not open file\n");
exit(-1);
}
else
{
while(0 ==feof(file))
{
i=fgetc(file);
printf("%c", i);
}
}
fclose(file);
return i;
}
file content:
10x16 ds5 h6,5 g7,8 p3,3
10X16 de4 h5,7 g9,2
10X16 dw6,h2,3 m6,7
10X16 dn3,h2,4 p2,3
10X16 de2 h9,9 m4,5
10X16 dn8 h4,5 g1,1*/
feof returns true if the last call to a read operation hit EOF. You'd want to test it after the fgetc call. Or, even better, just check whether fgetc returned the special value EOF.
(A FILE * has an "end-of-file marker" that says whether some read operation has hit EOF. Read operations set the "end-of-file marker" upon hitting EOF. Before you've hit---meaning tried to read past---the end of the file, that "end-of-file marker" is clear.)
Timing is bad than look at the beginning of the loop by feof because EOF occur in fgetc.
replace to
while(EOF!=(i=fgetc(file))){
printf("%c", i);
}
int filePrinter(char*arr){
int i = 0, ch;
FILE*file;
file=fopen("assests/room.txt","r");
if(file == NULL) {
printf("Could not open file\n");
exit(-1);
} else {
while(EOF!=(ch=fgetc(file))) {
//printf("%c", ch);
arr[i] = ch; //*arr++ = ch;
++i;//i : range check
}
arr[i] = '\0';
}
fclose(file);
return i;
}
I think the code should be:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void filePrinter(char*arr);
int main (int argc, char**argv)
{
char fileArray[150];
memset(fileArray, 0, sizeof(fileArray));
if(argc !=2)
{
printf("Invalid Entry. Please Enter name of program followed by input filename\n");
}
filePrinter(fileArray);
return 0;
}
void filePrinter(char *arr)
{
int c = 0, j = 0;
FILE* file = NULL;
file=fopen("assests/room.txt","r");
if(file == NULL)
{
printf("Could not open file\n");
exit(-1);
}
else
{
while (1)
{
c = fgetc(file);
if (c != EOF)
{
arr[j++] = c;
}
else
{
break;
}
}
}
fclose(file);
return;
}

Resources