Omnimaga

General Discussion => Technology and Development => Computer Programming => Topic started by: yrinfish on August 18, 2011, 03:09:10 am

Title: File reading with c/c++
Post by: yrinfish on August 18, 2011, 03:09:10 am
I want to be able to do this on a file:

Code: [Select]
myChar = getTheNthCharOrSomething(9);
that for example in pseudo-code, getTheNthCharOrSomething() is this:

Code: [Select]
char getTheNthCharOrSomething(where) {
    return file.charAt(where);
}

file is a global var.
Title: Re: File reading with c/c++
Post by: Juju on August 18, 2011, 03:29:59 am
Hmmm, good question. You would open a file, copy its contents in a string, then run a substr (http://www.cplusplus.com/reference/string/string/substr/) on it.
Title: Re: File reading with c/c++
Post by: yrinfish on August 18, 2011, 03:30:46 am
and how to copy it in a string?
Title: Re: File reading with c/c++
Post by: Juju on August 18, 2011, 03:36:11 am
Use fgets.

http://www.cplusplus.com/reference/clibrary/cstdio/fgets/
Title: Re: File reading with c/c++
Post by: yrinfish on August 18, 2011, 03:42:31 am
But I need whatever comes after a newline too
Title: Re: File reading with c/c++
Post by: Juju on August 18, 2011, 03:54:21 am
Ah, nevermind, I found a more efficient way. Use fseek (http://www.cplusplus.com/reference/clibrary/cstdio/fseek/) to seek to the nth character, then fgetc (http://www.cplusplus.com/reference/clibrary/cstdio/fgetc/) to get that character.