'Changing contents of a file
I'm trying to change the contents of a user specified file in a way that each character of the input file gets shifted by +5%127 according to their ASCII-code values.
My code is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main(int argc, char *argv[]){
char filename[100];
printf("Provide name of file:\n");
scanf("%s", filename);
FILE *fp;
fp = fopen(filename,"a+");
if(fp==0){
fprintf(stderr, "Error opening %s file!\n", filename);
exit(1);
}
else{
char c;
fseek(fp, 0, SEEK_SET);
while ((fgetc(fp)) != EOF)
{
fputc((c+5%127),fp);
}
}
}
The reason I'm using "a+" as argument in fopen(), is because I'm trying to resolve the issue seeing what it adds to the original file.
I am unsure why this isn't working. Currently it steps into an infinite loop, and just repeatedly change the first character but not the second, printing "changed first character, intact second characted" of the provided input file till I shut down the terminal window.
UPDATE #1:
else{
int c;
fseek(fp, 0, SEEK_SET);
while ((c = fgetc(fp)) != EOF){
fputc((c+5%127),fp);
}
}
But now it does UB.
Solution 1:[1]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
char filename[100];
printf("Provide name of file:\n");
scanf("%s", filename);
FILE *fp, *outfp;
fp = fopen(filename, "r");
outfp = fopen("out", "w+");
if (fp == 0) {
fprintf(stderr, "Error opening %s file!\n", filename);
exit(1);
} else {
int c;
fseek(fp, 0, SEEK_SET);
// This print statement will show you that what happen.
// You need to remove printf statement.
// => while ((c = fgetc(fp) != EOF) {
while ((c = fgetc(fp), printf("Get %d\n", c), c) != EOF) {
int result = (c + 5) % 127;
fputc(result, outfp);
}
}
}
You can read and write file at the same time. But ... is it a really good idea? If you use the mode a+ to deal with a file, the file struct will:
- First, you use the function
fgetc, now the file struct's position variable turn from 0 to 1. (point to the 1st byte now). - Then, you call the function
fputc, now because the file's mode isa+, it will try to move the position to the end-of-file. Then put the firstc + 5 % 127(?). - And then you try to use
fgetcagain. Now it find end-of-file, and return EOF. Then you jump out the while statement.
If you really want to read and write file at the same time, you can try:
- Read the file's content into your buffer and close the file pointer.
- Change the content in your buffer.
- Open the file by
writemode, and write into your file by your buffer.
:) Hope it is helpful.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
