Changing characters in a file using a buffer
Hi. I did this simple program to change the '<' characters to '>' in a file and vice-versa. However, when writing the new file the newlines got screwed up and there seems to be random spaces. It was compiled using Dev-cpp 4.9.2.
What is wrong? Should I instead read the file char by char using fgetc and do the changes directly instead using the char* buffer?
Code:
#include <stdio.h>
#include <string.h>
unsigned char* buf;
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: fix_ch file\n");
return -1;
}
char ch;
int size, status, i = 0;
FILE *fp = fopen(argv[1], "r+b");
if (fp == NULL)
{
printf ("Error opening file.\n");
return -1;
}
fseek (fp, 0 , SEEK_END);
size = ftell (fp);
rewind(fp);
buf = (char*)malloc(sizeof(char)*size);
fread(buf, 1, size, fp);
fclose(fp);
for (i = 0; i < size; i++)
{
if (buf[i] == '>')
{
buf[i] = '<';
status = 1;
}
if (buf[i] == '<' && status != 1)
{
buf[i] = '>';
}
status = 0;
}
fp = fopen(argv[1], "w");
for (i = 0; i < size; i++)
{
fputc(buf[i], fp);
}
return 0;
}