简体   繁体   中英

Read txt file from standard input and store whole text into char array

Let me describe what I am trying to do.

  1. Compile the source and run with an input text file

    gcc main.c -o main

    ./main < text.txt

  2. Then the text inside 'text.txt' should be stored into one single variable. I am not sure, but I think this should be as char array.

  3. Ultimately, I want loop through each character of 'text.txt' with its index; in python it should be like as follows

    i = 0
    
    while i < len(string):
    
        print(string[i])
    
        if (~~~):
    
            i -= 10(or some other numbers)
    
        else:
    
            i += 1

Several points to consider

  1. i can be decremented and print again from the i-10th character.
  2. The program doesn't know the length of the input text file.
  3. I cannot specify file directory in the source; the input text must come through standard input in the terminal.

How can I write this in C?

The following was my try in C, didn't work though.

int main(){
    char A;
    short i;

    scanf("%s", A);
    printf("%s", A);
    for (i=0; i < strlen(A); i++) {
        printf("%c", A[i]);
    }

    return 0;
}

You can do it multiple ways, lets start by getting proper length of file.

FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END); // goes to the end of file
long fsize = ftell(f); // tells what position in bytes is 
fclose (f)

f = fopen("textfile.txt", "r");

You noticed that I am using rb or read binary. thats because to get over the fact that if you use fseek() and ftell() in non binary mode you are getting into undefined behavior and results may differ between Windows machine and (*)nix machine.

Now how to read a text file into the string. There are multiple ways

  1. using getc() not preferred
  2. using fscanf() not preferred either, better than getc() in a way that it reads mutiple bytes at the time
  3. using fgets() you can specify the size of the file you read thus avoiding buffer overflow.

Above is quick and dirty way of reading, without knowing what is your DE like (what OS, compiler etc) I could go into more details how to do it, but tnx to @Nail here is an article , you can read. You could use it and have flags for different OSs instead of using my method.

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