Hello guys I m trying to code a program to fix indented code but problem is that i will use strstr to search for the for string then i ill read it till it encounted \0 then i wanna jump to next line to add 4 spaces before the code is there a way i can jump to next line ?

Dani AI

Generated

Short answer: read by line (or finish the current line) and then read the following line to add indentation. was pointing in that direction — once the rest of the current line has been consumed the next read returns the next line. Below is a small, practical pattern that avoids leaving the file pointer mid-line and shows a safe way to add four spaces to the line immediately after a for header.

/* copy input to output; if a line contains a standalone "for" token,
   read the next source line and write it out prefixed with 4 spaces */
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void) {
    FILE *in = fopen("in.c", "r");
    FILE *out = fopen("out.c", "w");
    char line[4096];

    while (fgets(line, sizeof line, in)) {
        fputs(line, out);               /* write current line unchanged */
        char *p = strstr(line, "for");  /* simple detection; refine as needed */
        if (p) {
            int ok = (p == line) || (!isalnum((unsigned char)p[-1]) && p[-1] != '_');
            if (ok) {
                if (fgets(line, sizeof line, in)) {   /* next line */
                    fputs("    ", out);               /* add 4 spaces */
                    fputs(line, out);
                }
            }
        }
    }
    fclose(in);
    fclose(out);
    return 0;
}

Notes and cautions: this is a minimal, heuristic approach. Real code needs to skip for inside comments or strings, handle multi-line for headers, and deal with braces on the same line. For robust formatting, consider using a parser-based tool (for example, clang-format or GNU indent) rather than ad-hoc text fixes; those tools understand the language and avoid many edge cases. If modifying files in-place, write to a temporary file and replace the original after success to avoid data loss.

Recommended Answers

All 5 Replies

Read the rest of the current line.

yah but how can i ? like for example i ill read for line this
for(i=0;buffer!=0;i++); but that will only read current line i wanna jump to next one like read the for then at end of the after it reached 0 i want to jump to next line to add 4 spaces

like lets say for example this code
for(CODE)
codeishere

it will move it
to
for(code)
codeishere

When you finish reading a line, you are automatically ready to read the next line. So just start reading again and there you are!

srry internet was off anyways i solved it thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.