简体   繁体   中英

Read own source file and text file line number?

We have a assignment and the teacher doesn't go into depth with explaining things so I'm a bit confused since I haven't really done much programming before. We have to write a program that when it's done being executed it's able to read its source file and can make another text file which is the same as its source file but the text file has a line number. My problem is I don't understand how to begin it. Could someone give me an example how to get started and what steps to take? I'm not asking for someone to do the programming for me just give an example. Thanks in advance.

Roughly the steps you'll want to take are:

  1. Read each line of the input text file
  2. Prepend the line number to the beginning of each line.
  3. Write your modified lines into a new text file.

There's a lot of good information on how to read/write to files here , and string concatenation (for how to prepend the line number) here . You may also want to look into for loops so that you can hit every line in the input file.

There are really two parts to your question: "Who am I?" (what file are you) and "Write a copy of myself with line numbers"

The part that you describe above is the first -- "Who am I?" and for that, something external to your source code has to provide the info because the language itself can reside in any file.

Often, there is information available about what's being compiled made available by the preprocessor (just like it sounds, it's something that is run before compiling your source code). In this case, "preprocessor macros" commonly give you this sort of environmental data.

Take a look at this link for GNU C: https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html to start researching what is available under what conditions. Your compiler, if not gcc, should have similar docs.

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