Let me describe what I am trying to do.
Compile the source and run with an input text file
gcc main.c -o main
./main < text.txt
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.
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
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
getc()
not preferredfscanf()
not preferred either, better than getc()
in a way that it reads mutiple bytes at the timefgets()
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.