简体   繁体   中英

Printing lines from a text file in reverse order

I am trying to read in the Constitution as a text file from the command line into my program to print out the lines in reverse order. My for loop looks like this:

for(int i = 0; i >= 0; i--) {
    if(strings[i] == '\0') //counts through array until it finds a line break
    { 
        break;
    }
    printf("%s", strings[i]);
}

When the program runs, the only thing that prints is the first line of the Constitution. If I modify my for loop to increment i, the program runs smoothly and outputs the Constitution like normal, and therefore I believe my entire problem is summed up in this for loop. This is the rest of my program for reference.

int clearBuffer() {
    char junk;
    while((junk = getchar()) != feof(stdin) && junk != '\n');
    return 0;
}

int getAline(char ** bufferPointer, int * sizePointer){ 
    char * buffer = *bufferPointer;
    int count = 0;
    int size = *sizePointer;
    while(!feof(stdin)){
        if(count >= size - 1){
            char * tempBuffer = (char * )malloc(size * 10); 
            //strcpy(tempBuffer, buffer );
            for (int i = 0; i < size; i++){
                tempBuffer[i] = buffer[i];
                //putchar(tempBuffer[i]);
            }
            free(buffer);
            buffer = tempBuffer;
            size *= 10;
        }
        buffer[count] = getchar();

        if(buffer[count] == '\n'){
            break;      
        }
        if(buffer[count] == EOF){
            buffer[count] = '\0';
            break;
        }

        count++;
    }
    *bufferPointer = buffer;
    *sizePointer = size;
    return count-1;
    }

int main(){

    char * buffer;

    char * strings[1000]; 


    int arrayCount =0;
    int size = 10;

    while(!feof(stdin))
    {
        buffer= (char*) malloc(size);
        getAline(&buffer, &size);

        strings[arrayCount++] = buffer;
    }

    for(int i = 0; i >= 0; i--) {
        if(strings[i] == '\0'){
            break;
        }
        printf("%s", strings[i]);
    }
    return 0;
}

When you reverse a loop's iteration direction, you also have to reverse the beginning and ending values.

for(int i = arrayCount-1; i >= 0; i--)

Now, this loop starts at the end, then works back down to the beginning of the array.

使int i等于Constitution中的行数,而不是应该执行的0。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM