I am assigned to convert all strings to lowercase in a txt file and then output it in a new txt file but i cant seem find anywhere how to do it. Any help would be very appriciated! Thank you This is what i have till now but there is the y at the end so im thinking if there is a better way to do it or if i can remove the y with the two dots on top..
#include<stdio.h>
#include<process.h>
void main() {
FILE *fp1, *fp2;
char a;
fp1 = fopen("test.txt", "r");
if (fp1 == NULL)
{
puts("cannot open this file");
exit(1);
}
fp2 = fopen("test1.txt", "w");
if (fp2 == NULL) {
puts("Not able to open this file");
fclose(fp1);
exit(1);
}
do
{
a = fgetc(fp1);
a = tolower(a);
fputc(a, fp2);
} while (a != EOF);
fcloseall();
getch();
}
When you read input from a file, you should always check whether you get valid input before proceeding to use it. In your case, you get input in the line.
a = fgetc(fp1);
You need to check whether a
is valid input before proceeding to use it.
if ( a != EOF )
{
a = tolower(a);
fputc(a, fp2);
}
Another thing to update. Don't use
char c;
Use
int c;
instead.
char
type can be a signed type or unsigned type on your platform. If it is an unsigned type, it will never have a negative value. Hence, it will never equal EOF
, which is -1
often, which will lead to an infinite loop.
If you lookup the documentation of fgetc
, you will notice that its return type is int
, not char
.
Your program can be updated to something like:
void main() {
FILE *fp1, *fp2;
int a;
// Add rest of your code
// ...
do
{
a = fgetc(fp1);
if ( a != EOF )
{
a = tolower(a);
fputc(a, fp2);
}
} while (a != EOF);
// Add rest of your code
// ...
}
The do-while
loop can be simplified to:
while ( (a = fgetc(fp1)) != EOF )
{
a = tolower(a);
fputc(a, fp2);
}