I was writing a tool that replaces enough spaces with tab, but it counts more spaces than expected.
Algorithm should count spaces until seeing character or newline, if there is a character or newline, it passes to next element of string; but unfortunately continues to count spaces instead of passing newline or character.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#define BUFFER_SIZE 100
int set_tab_init_arg(char *filename, int space_size)
{
struct stat filest;
FILE *fp = fopen(filename, "r+");
int fd = fileno(fp);
int line = 0, space = 0, var = 0, offset = 0;
if (fstat(fd, &filest) < 0)
return -1;
char *filecontent = (char*)malloc(filest.st_size);
char buff[BUFFER_SIZE];
if (fp == NULL) {
fprintf(stderr, "cyntax: invalid file pointer!\n");
return -1;
}
while (fgets(buff, BUFFER_SIZE, fp) != NULL)
strcat(filecontent, buff);
char *tmpcontent, *willbewrited = filecontent;
for (int x = 0; x < strlen(filecontent); x++) {
if (filecontent[x] == 32) {
printf("space\n");
space++;
}
else if (filecontent[x++] == 10) {
line++;
printf("newline: %d\n", line);
space = 0;
}
else {
printf("char\n");
x++;
var++;
}
if (space == space_size) {
replace_spaces_to_tab();
printf("space = space_size\n");
}
filecontent++, offset++;
}
}
here is file I tested on:
a
b
c
d
e f g
c h e
p ğ a
and debug result is here (stdout):
space
newline: 1
newline: 2
newline: 3
newline: 4
space
space
space = space_size
newline: 5
space
space
space = space_size
newline: 6
space
char
I executed with parameters:
./cyntax try -t 2
Note-1: try
is file and -t 2
gets space size for converting enough spaces to tab.
Note-2: I used printf() function for debugging.