learn_c/intro/ex1_21_entab.c

59 lines
1.1 KiB
C
Raw Permalink Normal View History

2023-11-13 23:00:40 +00:00
#include <stdio.h>
#define MAXLINE 1000 /* maximum characters in a line */
#define TABWIDTH 4 /* tab size */
int my_getline(char line[], int maxline);
2023-11-14 21:10:20 +00:00
void entab(char to[], char from[]);
2023-11-13 23:00:40 +00:00
main()
{
int len; /* current line length */
char line[MAXLINE]; /* current input line */
2023-11-14 21:10:20 +00:00
char entab_line[MAXLINE]; /* detabbed line */
2023-11-13 23:00:40 +00:00
2023-11-14 21:10:20 +00:00
while ((len = my_getline(line, MAXLINE)) > 0) {
entab(entab_line, line);
printf("%s", entab_line);
}
2023-11-13 23:00:40 +00:00
return 0;
}
/* my_getline: reads in a line, return the length */
int my_getline(char line[], int lim)
{
int c, i;
for (i = 0; i < lim-1 && (c=getchar()) != EOF && c != '\n'; ++i)
line[i] = c;
if (c == '\n') {
line[i] = c;
++i;
}
line[i] = '\0';
return i;
}
2023-11-14 21:10:20 +00:00
/* entab: replace blanks with tab in line; does not handle the limit */
void entab(char to[], char from[])
2023-11-13 23:00:40 +00:00
{
int i, j, k;
i = j = k = 0;
while ((to[j] = from[i]) != '\0') {
2023-11-14 21:10:20 +00:00
if (from[i] == ' ') {
++k;
if (k == TABWIDTH) {
k = 0;
j = j - TABWIDTH;
to[j] = '\t';
}
} else {
k = 0;
}
++j;
2023-11-13 23:00:40 +00:00
++i;
}
}