Well I try to read a file and change every word that's beginning with a lowercase to the same word beginning with an uppercase.
This is what i got:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int zeichen;
fp = fopen("test.txt", "r+");
if(fp == NULL){
printf("Die Datei konnte nicht geoeffnet werden.\n");
}
else{
fseek(fp, 0L, SEEK_SET);
zeichen = fgetc(fp);
while(zeichen != EOF){
if(zeichen == ' '){
fseek(fp, 1L, SEEK_CUR);
if(('a' <= zeichen) && (zeichen <= 'z')){
zeichen = fgetc(fp);
fputc(toupper(zeichen), fp);
}
}
zeichen = fgetc(fp);
}
zeichen = fgetc(fp);
fclose(fp);
}
return 0;
}
My test.txt file does not change at all.
Any suggestions what i am doing wrong?
EDIT:
Thank you for the different ways to achieve my task.
Most of them where using stuff i didn't learn yet, so i tried it by copying the characters from one file to another + making the first letter of each word an uppercase by toupper() cause it's indeed easy to use. Then deleting the old file + rename the new one.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
FILE *fp, *neu;
int zeichen;
fp = fopen("test.txt", "r");
neu = fopen("new.txt", "w");
if(fp == NULL) {
printf("Die Datei konnte nicht geoeffnet werden.\n");
exit(EXIT_FAILURE);
}
while((zeichen = fgetc(fp)) != EOF) {
if(zeichen == ' ') {
fputc(zeichen, neu);
zeichen = fgetc(fp);
zeichen = toupper(zeichen);
fputc(zeichen, neu);
}
else{
fputc(zeichen, neu);
}
}
fclose(fp);
fclose(neu);
remove("test.txt");
rename("new.txt", "test.txt");
printf("File has been changed.\n");
return 0;
}
FILE *fp;
int zeichen;
fp = fopen("test.txt", "r+");
if (fp == NULL) {
printf("Die Datei konnte nicht geoeffnet werden.\n");
exit(EXIT_FAILURE);
}
// upper first charcter
zeichen = getc(fp);
if (zeichen != EOF) putchar(toupper(zeichen));
// scan rest of chars
while ((zeichen = getc(fp)) != EOF) {
putchar(zeichen);
if (zeichen == ' ' && zeichen != EOF) {
char c_upper = getc(fp);
putchar(toupper(c_upper));
}
}
fclose(fp);
return 0;
you can use std out redirection ./main > output.txt