C Read and replace char - c

I'm trying to read a file and replace every char by it's corresponding char up one in ASCII table. It opens the file properly but keep on reading the first character.
int main(int argc, char * argv[])
{
FILE *input;
input = fopen(argv[2], "r+");
if (!input)
{
fprintf(stderr, "Unable to open file %s", argv[2]);
return -1;
}
char ch;
fpos_t * pos;
while( (ch = fgetc(input)) != EOF)
{
printf("%c\n",ch);
fgetpos (input, pos);
fsetpos(input, pos-1);
fputc(ch+1, input);
}
fclose(input);
return 1;
}
the text file is
abc
def
ghi
I'm pretty sure it's due to the fgetpos and fsetpos but if I remove it then it will add the character at the end of the file and the next fgetc will returns EOF and exit.

You have to be careful when dealing with files opened in update mode.
C11 (n1570), § 7.21.5.3 The fopen function
When a file is opened with update mode ('+' as the second or third character in the
above list of mode argument values), both input and output may be performed on the
associated stream.
However, output shall not be directly followed by input without an
intervening call to the fflush function or to a file positioning function (fseek,
fsetpos, or rewind), and input shall not be directly followed by output without an
intervening call to a file positioning function, unless the input operation encounters end-of-file.
So your reading might look something like :
int c;
while ((c = getc(input)) != EOF)
{
fsetpos(/* ... */);
putc(c + 1, input);
fflush(input);
}
By the way, you will have problems with 'z' character.

procedure for performing random access such
positioned the record
reading of the record
positioned the record
update(write) the record
do flush (to finalize the update)
The following code is a rewrite in consideration to it.
#include <stdio.h>
#include <ctype.h>
int main(int argc, char * argv[]){
FILE *input;
input = fopen(argv[1], "rb+");
if (!input){
fprintf(stderr, "Unable to open file %s", argv[1]);
return -1;
}
int ch;
fpos_t pos, pos_end;
fgetpos(input, &pos);
fseek(input, 0L, SEEK_END);
fgetpos(input, &pos_end);
rewind(input);
while(pos != pos_end){
ch=fgetc(input);
if(EOF==ch)break;
printf("%c",ch);
if(!iscntrl(ch) && !iscntrl(ch+1)){
fsetpos(input, &pos);
fputc(ch+1, input);
fflush(input);
}
pos += 1;
fsetpos(input, &pos);
}
fclose(input);
return 1;
}

I really suspect the problem is here:
fpos_t * pos;
You are declaring a pointer to a fpos_t which is fine but then, where are the infomation stored when you'll retrieve the pos?
It should be:
fpos_t pos; // No pointer
...
fgetpos (input, &pos);
fsetpos(input, &pos); // You can only come back where you were!
Reading the (draft) standard, the only requirement for fpos_t is to be able to represent a position and a state for a FILE, it doesn't seem that there is a way to move the position around.
Note that the expression pos+1 move the pointer, does not affect the value it points to!
What you probably want is the old, dear ftell() and fseek() that will allow you to move around. Just remember to open the file with "rb+" and to flush() after your fputc().
When you'll have solved this basic problem you will note there is another problem with your approach: handling newlines! You most probably should restrict the range of characters you will apply your "increment" and stipulate that a follows z and A follows Z.
That said, is it a requirement to do it in-place?

7.21.9.1p2
The fgetpos function stores the current values of the parse state (if
any) and file position indicator for the stream pointed to by stream
in the object pointed to by pos. The values stored contain unspecified
information usable by the fsetpos function for repositioning the
stream to its position at the time of the call to the fgetpos
function.
The words unspecified information don't seem to inspire confidence in that subtraction. Have you considered calling fgetpos prior to reading the character, so that you don't have to do a non-portable subtraction? Additionally, your call to fgetpos should probably pass a pointer to an existing fpos_t (eg. using the &address-of operator). Your code currently passes a pointer to gibberish.
fgetc returns an int, so that it can represent every possible unsigned char value distinct from negative EOF values.
Suppose your char defaults to an unsigned type. (ch = fgetc(input)) converts the (possibly negative, corresponding to errors) return value straight to your unsigned char type. Can (unsigned char) EOF ever compare equal to EOF? When does your loop end?
Suppose your char defaults, instead, to a signed type. (c = fgetc(input)) is likely to turn the higher range of any returned unsigned char values into negative numbers (though, technically, this statement invokes undefined behaviour). Wouldn't your loop end prematurely (eg. before EOF), in some cases?
The answer to both of these questions indicates that you're handing the return value of fgetc incorrectly. Store it in an int!
Perhaps your loop should look something like:
for (;;) {
fpos_t p;
/* TODO: Handle fgetpos failure */
assert(fgetpos(input, &p) == 0);
int c = fgetc(input);
/* TODO: Handle fgetc failure */
assert(c >= 0);
/* TODO: Handle fsetpos failure */
assert(fsetpos(input, &p) == 0);
/* TODO: Handle fputc failure */
assert(fputc(c + 1, input) != EOF);
/* TODO: Handle fflush failure (Thank Kirilenko for this one) */
assert(fflush(input) == 0);
}
Make sure you check return values...

The update mode('+') can be a little bit tricky to handle. Maybe You could just change approach and load the whole file into char array, iterate over it and then eventually write the whole thing to an emptied input file? No stream issues.

Related

Why should I put SEEK_SET twice

I want to modify some vowels of a file by "5". The following code works. However, I do not understand why I should put fseek twice.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void print_file_contents(const char *filename)
{
FILE *fp;
char letter;
if((fp=fopen(filename,"r+"))==NULL)
{
printf("error\n");
exit(1);
}
fseek(fp,0,SEEK_END);
int size=ftell(fp);
rewind(fp);
for(int i=0;i<size;i++)
{
fseek(fp,i,SEEK_SET);
letter=fgetc(fp);
if((letter=='a') || (letter=='e') || (letter=='i'))
{
fseek(fp,i,SEEK_SET); // WHY THIS FSEEK ?
fwrite("5",1,sizeof(char),fp);
}
}
fclose(fp);
}
int main(int argc, char *argv[])
{
print_file_contents("myfile");
return 0;
}
In my opinion, the first fseek(fp, i, SEEK_SET) is used to set the file position indicator to the current character being processed, so that the character can be read using fgetc. Hence, the cursor is updated every time so there is no need to add another fseek(fp, i, SEEK_SET);.
The fgetc advanced the file position; if you want to replace the character you just read, you need to rewind back to the same position you were in when you read the character to replace.
Note that the C standard mandates a seek-like operation when you switch between reading and writing (and between writing and reading).
§7.21.5.s The fopen function ¶7:
¶7 When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end- of-file.
Also, calling fgetc() moves the file position forward one character; if the write worked (it's undefined behaviour if you omit the seek-like operation), you'd overwrite the next character, not the one you just read.
Your intuition is correct: two of the three fseek calls in this program are unnecessary.
The necessary fseek is the one inside the if((letter=='a') || (letter=='e') || (letter=='i')) conditional. That one is needed to back up the file position so you overwrite the character you just read (i.e. the vowel), not the character after the vowel.
The fseek inside the loop (but outside the if) is unnecessary because both fgetc and fwrite advance the file position, so it will always set the file position to the position it already has. And the fseek before the loop is unnecessary because you do not need to know how big the file is to implement this algorithm.
This code can be tightened up considerably. I'd write it like this:
#include <stdio.h>
void replace_aie_with_5_in_place(const char *filename)
{
FILE *fp = fopen(filename, "r+"); // (1)
if (!fp) {
perror(filename); // (2)
exit(1);
}
int letter;
while ((letter = fgetc(fp)) != EOF) { // (3)
if (letter == 'a' || letter == 'e' || letter == 'i') { // (4)
fseek(fp, -1, SEEK_CUR); // (5)
fputc('5', fp);
if (fflush(fp)) { // (6)
perror(filename);
exit(1);
}
}
if (fclose(fp)) { // (7)
perror(filename);
exit(1);
}
}
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "usage: %s filename\n", argv[0]);
return 1;
}
replace_aei_with_5_in_place(argv[1]); // (8)
return 0;
}
Notes:
It is often (but not always) better to write operations with side effects, like fopen, separately from conditionals checking whether they succeeded.
When a system-level operation fails, always print both the name of any file involved, and the decoded value of errno. perror(filename) is a convenient way to do this.
You don't need to know the size of the file you're crunching because you can use a loop like this, instead. Also, this is an example of an exception to (1).
Why not 'o' and 'u' also?
Here's the necessary call to fseek, and the other reason you don't need to know the size of the file: you can use SEEK_CUR to back up by one character.
This fflush is necessary because we're switching from writing to reading, as stated in Jonathan Leffler's answer. Inconveniently, it also consumes the notification for some (but not all) I/O errors, so you have to check whether it failed.
Because you are writing to the file, you must also check for delayed I/O errors, reported only on fclose. (This is a design error in the operating system, but one that we are permanently stuck with.)
Best practice is to pass the name of the file to munge on the command line, not to hardcode it into the program.
#Jonathan Leffler well states why code used multiple fseek(): To cope with changing between reading and writing.
int size=ftell(fp); is weak as the range of returned values from ftell() is long.
Seeking in a text file (as OP has) also risks undefined behavior (UB).
For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET. C17dr § 7.21.9.1 3.
Better to use #zwol like approach with a small change.
Do not assume a smooth linear mapping. Instead, note the location and then return to it as needed.
int replacement = '5';
for (;;) {
long position = ftell(fp);
if (ftell == -1) {
perror(filename);
exit(1);
}
int letter = fgetc(fp);
if (letter == EOF) {
break;
}
if (letter == 'a' || letter == 'e' || letter == 'i') {
fseek(fp, position, SEEK_SET);
fputc(replacement, fp);
if (fflush(fp)) {
perror(filename);
exit(1);
}
}
}
Research fgetpos(), fsetpos() for an even better solution that handles all file sizes, even ones longer than LONG_MAX.

how ftell() function works?

I have this code and I don't understand how it works:
void print(char * fileName)
{
FILE * fp;
int ch;
fp = fopen(fileName, "r");
while (ftell(fp) < 20)
{
ch = fgetc(fp);
putchar(ch);
}
fclose(fp);
}
So how is ftell(fp) works if it is in loop?
Because there is nothing inside the loop that get it up.
how it is progressive?
ftell() gets you the current value of the position indicator of the stream(in your case, it basically returns the character position it is currently pointing to right now).
fgetc() gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream. This function returns the character read as an unsigned char cast to an int or EOF on end of file or error
Flow of your program
What that means in very simple terms is -
fgetc() is reading one character after character from the file and advancing the pointer to the next character.
ftell() is returning you the current position in in bytes from the
beginning of the file. This means it tells the position of the character it is pointing right now(since 1 char takes 1 byte).
So, your program reads from the file until ftell() returns the
position which is less than 20.This means that it will keep looping until 20 characters have been read from your file.
Hope this clears your doubt !
ftell returns the current value of the file position indicator, and fgetc does advance the file position indicator within the loop.
But this program is wrong. For a stream opened in text mode ("r"), the return value of ftell cannot be used portably for anything else except for seeking to a previous position. From C11 draft n1570 7.21.9.4p2
[...] For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.
Indeed it doesn't make any sense to use ftell in this program. Either open the file in binary mode, "rb", and then it is guaranteed that
[...] the value is the number of characters from the beginning of the file.
or for counting characters read from text file, use a counter variable:
int c_read = 0;
while (c_read < 20)
{
ch = fgetc(fp);
putchar(ch);
c_read ++;
}
Finally neither your original version or mine does not work correctly if the file has less than 20 characters. In that case EOF is returned from fgetc and putchar would write (unsigned char)EOF to the stream (most likely a byte of value 255!)
Thus the correct code would be
int c_read = 0;
while (c_read < 20)
{
ch = fgetc(fp);
if (ch == EOF) {
// report the error
perror("Failed to read 20 characters");
break;
}
putchar(ch);
c_read ++;
}

I am getting unexpected output in this Program

I just want to replace specific character from file.
for example, I want to replace character 'l' with character 'p'.
is it correct way ?
int main() {
FILE * ptr;
ptr = fopen("D:\f4.txt", "r+");
if (ptr == NULL) {
printf("file cant be opened");
exit(0);
}
char ch = fgetc(ptr);
while (ch != EOF) {
if (ch == 'l') {
fseek(ptr, -1, 1);
fputc('p', ptr);
}
ch = fgetc(ptr);
}
fclose(ptr);
}
suppose content in my file is "hello everyone" so output should be like "heppo everyone" but it writes in file "hepepepepepepepepepepepepepepep" continuesly. please help me to find why this happen.
Please note this from the man page for fopen().
When the "r+", "w+", or "a+" access type is specified, both reading and writing are enabled (the file is said to be open for "update"). However, when you switch from reading to writing, the input operation must encounter an EOF marker. If there is no EOF, you must use an intervening call to a file positioning function. The file positioning functions are fsetpos, fseek, and rewind. When you switch from writing to reading, you must use an intervening call to either fflush or to a file positioning function. (my italics)
So after you wrote 'p' to the file, it is not enough to carry on reading as though nothing has happened, you must fseek to the original position, obtained by ftell, or fflush the file.
Also don't use magic numbers: in fseek you should use SEEK_CUR not 1.
Finally, function fgetc returns an int type, not char. This allows EOF to be distinguished from the data byte 0xFF.

how to print all character from file with its position in c?

hello i wrote below a program in c,
#include <stdio.h>
#include <conio.h>
void main()
{
FILE *fp;
char c;
long n=0L;
fp=fopen("myfile.txt","w");
printf("Enter the data into file:\n");
while((c=getchar())!=EOF)
{
putc(c,fp);
}
printf("Total character into file:%ld\n",ftell(fp));
fclose(fp);
fp=fopen("myfile.txt","r");
while(feof(fp)==0)
{
fseek(fp,n,0);
printf("\n char:'%c' at position '%ld'",getc(fp),ftell(fp));
n++;
}
fclose(fp);
getch();
}
it work fine but when i replace the statement:
printf("\n char:'%c' at position '%ld'",getc(fp),ftell(fp));
with the statement:
printf("\n position '%ld'",ftell(fp));
then it will going to infinite loop
I knew the function, fseek()It set the file pointer to specified position.
but here what happen,i don't understand.
please help me.
Reason for infinite loop : In your second case you do not progress the stream as in first case
getc()
Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced to the next character.
A solution :
#include <stdio.h>
void main()
{
FILE *fp;
char c;
long n = 0L;
fp=fopen("main.c","r");
while(getc(fp)!=EOF)
{
fseek(fp,n,0);
printf("\n position '%ld'",ftell(fp));
n++ ;
}
fclose(fp);
}
Furthermore :
fseek() do not progress the file pointer.
Sets the position indicator associated with the stream to a new position.
feof()
This indicator is generally set by a previous operation on the stream
that attempted to read at or past the end-of-file."
So this explains your failure. Second implementation does not come across EOF as first case. Provided sample of code would provide you an workaround.
Check in documentation if fseek or ftell sets feof() result. Possibly not, so when you removed getc call feof can no longer return 'true', hence infinite loop.
Anyway, are you interested in the explanation why this program behaves strange or rather how you should write your program properly to achieve the result described...?
fseek() will not set the EOF marker, and in fact it can unset the EOF marker and it should do it after a succesful call.
Also, as the link points out the while (feof(fp) == 0) is always wrong, it's because you need to fgetc() one extra char for the EOF marker to be set, so you will have one extra iteration, instead you have to do it this way
#include <stdio.h>
int main()
{
FILE *fp;
int c; /* this should be 'int' and not 'char' */
long int n;
fp = fopen("myfile.txt", "w");
if (fp == NULL)
return -1;
printf("Enter the data into file:\n");
while ((c = getchar()) != EOF)
putc(c, fp);
printf("Total character into file:%ld\n", ftell(fp));
fclose(fp);
fp = fopen("myfile.txt","r");
if (fp == NULL)
return -1;
while ((c = fgetc(fp)) != EOF)
{
if (c == '\n')
printf("charcater `\\n' at position '%ld'\n", ftell(fp));
else
printf("charcater `%c' at position '%ld'\n", c, ftell(fp));
n++;
}
fclose(fp);
return 0;
}
A successful call fseek function clear the end-of-file indicator, but your loop condition rely on feof, so feof(fp) == 0 always true.
fseek(SEEK_SET) merely sets the FILE's pointer to a position in the file. It doesn't actually do any reading of the file or anything. So, it will gladly let you set the position to WAY past the end of the file (and it clears any existing EOF set on the stream). ftell() merely returns the position of the file pointer.
Without doing a read of some sort (e.g. - getc()), EOF won't be set on the stream and your loop will be infinite.
You can do a fseek(fp, 0, SEEK_END) and then an ftell() to know the size / end of the file position.
PS - You really need to check your return values more carefully and handle any failures.

While (( c = getc(file)) != EOF) loop won't stop executing

I can't figure out why my while loop won't work. The code works fine without it... The purpose of the code is to find a secret message in a bin file. So I got the code to find the letters, but now when I try to get it to loop until the end of the file, it doesn't work. I'm new at this. What am I doing wrong?
main(){
FILE* message;
int i, start;
long int size;
char keep[1];
message = fopen("c:\\myFiles\\Message.dat", "rb");
if(message == NULL){
printf("There was a problem reading the file. \n");
exit(-1);
}
//the first 4 bytes contain an int that tells how many subsequent bytes you can throw away
fread(&start, sizeof(int), 1, message);
printf("%i \n", start); //#of first 4 bytes was 280
fseek(message, start, SEEK_CUR); //skip 280 bytes
keep[0] = fgetc(message); //get next character, keep it
printf("%c", keep[0]); //print character
while( (keep[0] = getc(message)) != EOF) {
fread(&start, sizeof(int), 1, message);
fseek(message, start, SEEK_CUR);
keep[0] = fgetc(message);
printf("%c", keep[0]);
}
fclose(message);
system("pause");
}
EDIT:
After looking at my code in the debugger, it looks like having "getc" in the while loop threw everything off. I fixed it by creating a new char called letter, and then replacing my code with this:
fread(&start, sizeof(int), 1, message);
fseek(message, start, SEEK_CUR);
while( (letter = getc(message)) != EOF) {
printf("%c", letter);
fread(&start, sizeof(int), 1, message);
fseek(message, start, SEEK_CUR);
}
It works like a charm now. Any more suggestions are certainly welcome. Thanks everyone.
The return value from getc() and its relatives is an int, not a char.
If you assign the result of getc() to a char, one of two things happens when it returns EOF:
If plain char is unsigned, then EOF is converted to 0xFF, and 0xFF != EOF, so the loop never terminates.
If plain char is signed, then EOF is equivalent to a valid character (in the 8859-1 code set, that's ÿ, y-umlaut, U+00FF, LATIN SMALL LETTER Y WITH DIAERESIS), and your loop may terminate early.
Given the problem you face, we can tentatively guess you have plain char as an unsigned type.
The reason that getc() et al return an int is that they have to return every possible value that can fit in a char and also a distinct value, EOF. In the C standard, it says:
ISO/IEC 9899:2011 §7.21.7.1 The fgetc() function
int fgetc(FILE *stream);
If the end-of-file indicator for the input stream pointed to by stream is not set and a
next character is present, the fgetc function obtains that character as an unsigned char converted to an int ...
If the end-of-file indicator for the stream is set, or if the stream is at end-of-file, the end-of-
file indicator for the stream is set and the fgetc function returns EOF.
Similar wording applies to the getc() function and the getchar() function: they are defined to behave like the fgetc() function except that if getc() is implemented as a macro, it may take liberties with the file stream argument that are not normally granted to standard macros — specifically, the stream argument expression may be evaluated more than once, so calling getc() with side-effects (getc(fp++)) is very silly (but change to fgetc() and it would be safe, but still eccentric).
In your loop, you could use:
int c;
while ((c = getc(message)) != EOF) {
keep[0] = c;
This preserves the assignment to keep[0]; I'm not sure you truly need it.
You should be checking the other calls to fgets(), getc(), fread() to make sure you are getting what you expect as input. Especially on input, you cannot really afford to skip those checks. Sooner, rather than later, something will go wrong and if you aren't religiously checking the return statuses, your code is likely to crash, or simply 'go wrong'.
There are 256 different char values that might be returned by getc() and stored in a char variable like keep[0] (yes, I'm oversummarising wildly). To detect end-of-file reliably, EOF has to have a value different from all of them. That's why getc() returns int rather than char: because a 257th distinct value for EOF wouldn't fit into a char.
Thus you need to store the value returned by getc() in an int at least until you check it against EOF:
int tmpc;
while( (tmpc = getc(message)) != EOF) {
keep[0] = tmpc;
...

Resources