cbufferlseek

How to change some letter in a file with the buffer and lseek


i'm having some trouble using lseek and the buffer for an assigment. The objective is to read a file and change every letter 'a' to a '?'. I'm running some minor programs to understand how the functions and buffer works and i'm having some trouble.. Imagine that my file "teste" has only "abcabcabc" in it. If i do this:

int fd = open("teste", O_RDWR);
char buf[1];
int fptr = lseek(fd, 0, SEEK_SET);
fflush(stdout);
read(fd, buf, 1);
printf("%s\n", buf);

i get on my console "a", so it reads well the first letter, because i put the pointer to the beggining. But if i do a if condition before the printf, comaparing buf to 'a', like:

if(buf == 'a') printf("%s\n", buf);

It doesn't work, it doesn't print anything, so it doesn't enter the if statement.. I need to compare the buffer to letters so i can change all 'a' of the file.. How can i do this guys?

Ok, this part is already solved due to the answers bellow, but now i'm trying to read all the file and compare each charecter to 'a', making a simple printf just to see if it's working.. i wrote this:

int fd = open("teste", O_RDWR);
char buf[1];
int fptr = lseek(fd, 1, SEEK_SET);
fflush(stdout);
read(fd, buf, 1);
while(fptr > 0){
  read(fd, buf, 1);
  if(buf[0] == 'a'){
    printf("%s\n",buf);
  }
  fflush(stdout);
  fptr=lseek(fd, (off_t)(1), SEEK_CUR);
}
close(fd);

But it's now working.. It prints only one'a', and then doesn't close and don't do anything.. Its like an infinite cycle but without entering the if statement. What's wrong?


Solution

    1. printf("%s\n", buf); is UB. %s wants a NULL terminated string. Use printf("%c\n", buf[0]);
    2. if(buf == 'a') must be if(buf[0] == 'a'). You are comparing address of buf with 'a' char but you want to compare the content of first (an unique) cell of buf array.