I'm dealing with small text files that i want to read into a buffer while i process them, so i've come up with the following code:  ... char source[1000000];  FILE *fp = fopen("TheFile.txt", "r"); if(fp != NULL) {     while((symbol = getc(fp)) != EOF)     {         strcat(source, &amp;symbol);     }     fclose(fp); } ...   Is this the correct way of putting the contents of the file into the buffer or am i abusing strcat()?  I then iterate through the buffer thus:  for(int x = 0; (c = source[x]) != '\0'; x++) {     //Process chars }
21332
What is the simplest way (least error-prone, least lines of code, however you want to interpret it) to open a file in C and read its contents into a string (char*, char[], whatever)?
32342
Is there a (cross-platform) way to get a C FILE* handle from a C++ std::fstream ?  The reason I ask is because my C++ library accepts fstreams and in one particular function I'd like to use a C library that accepts a FILE*.
64766
When I make a call to the C string compare function like this:  strcmp("time","time")  It returns 0, which implies that the strings are not equal.  Can anyone tell me why C implementations seem to do this? I would think it would return a non-zero value if equal. I am curious to the reasons I am seeing this behavior.
13470
I am a little surprised by the following.  Example 1:  char s[100] = "abcd"; // declare and initialize - WORKS   Example 2:  char s[100]; // declare s = "hello"; // initalize - DOESN'T WORK ('lvalue required' error)   I'm wondering why the second approach doesn't work. It seems natural that it should (it works with other data types)? Could someone explain me the logic behind this?
2343
I've been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I've visited.  Is there a better/different way to read a file into a string in Java?  private String readFile(String file) throws IOException {     BufferedReader reader = new BufferedReader(new FileReader (file));     String         line = null;     StringBuilder  stringBuilder = new StringBuilder();     String         ls = System.getProperty("line.separator");      try {         while((line = reader.readLine()) != null) {             stringBuilder.append(line);             stringBuilder.append(ls);         }          return stringBuilder.toString();     } finally {         reader.close();     } }
19556
Yes,  but there must be a canonical or most efficient or most concise way. I'll add answers I know of and see what percolates to the top.  To be clear, the question is how best to read the contents of a file into a string. One solution per answer.
33856
I want to display all the characters in a file between strings "xxx" and "yyy" (the quotes are not part of the delimiters). How can I do that ? For example, if i have input "Hello world xxx this is a file yyy", the output should be " this is a file "
2376
I was surprised to find today that I couldn't track down any simple way to write the contents of an InputStream to an OutputStream in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer).  So, given an InputStream in and an OutputStream out, is there a simpler way to write the following?  byte[] buffer = new byte[1024]; int len = in.read(buffer); while (len != -1) {     out.write(buffer, 0, len);     len = in.read(buffer); }
93317
I'm learning how to write programs in C using the k&amp;r book (The C Programming Language) and I have a problem with one of the exercises. It's asking me to detect and remove a character in string s1, which matches any characters in the string s2.  So, say s1 = "A";  And s2 = "AABAACAADAAE"  I want it to return "BCDE"  I know I'm on the right path towards it, i just don't know how to design programs very well, could you give me any additional tips. I tried to read about the binary search tree algorithm, but felt it was a little too advanced for this mundane task.  Thanks everyone!  /* An alternate version of squeeze(s1, s2) that deletes each character in  * s1 that matches any character in the string s2  *  * Angie@odfx.org  */  #include &lt;stdio.h&gt; #include &lt;string.h&gt;  void squeeze(char s[], char t[]);  char string[] = "BAD"; char sstring[] = "ABC";  int main(void) {     squeeze(string, sstring);     return 0; }  void squeeze(char s[], char t[]) {     int i, j, d;      d = 0;     if(strstr(s, t) == NULL)         printf("%c", s[i]);     s[j] = '\0'; }
76187
How can I test whether a command's output is an empty string while not   interfering with buffering?  Example:  command | ??? if [ $? = 0 ] &amp;&amp; [ -n "$output_from_command"]; then    ...   I want the output from the code above to be the same as when running command.
68837
So I'm working on an exceedingly large codebase, and recently upgraded to gcc 4.3, which now triggers this warning:     warning: deprecated conversion from string constant to ‘char*’   Obviously, the correct way to fix this is to find every declaration like  char *s = "constant string";   or function call like:  void foo(char *s); foo("constant string");   and make them const char pointers.  However, that would mean touching 564 files, minimum, which is not a task I wish to perform at this point in time.  The problem right now is that I'm running with -werror, so I need some way to stifle these warnings.  How can I do that?
81943
How does one parse an integer to string(char* || char[]) in C? Is there an equivalent to the Integer.parseInt(String) method from Java in C?
11028
The following C++ code uses a ifstream object to read integers from a text file (which has one number per line) until it hits EOF. Why does it read the integer on the last line twice? How to fix this?  Code:  #include &lt;iostream&gt; #include &lt;fstream&gt; using namespace std;  int main() {     ifstream iFile("input.txt");    // input.txt has integers, one per line      while (!iFile.eof())     {         int x;         iFile &gt;&gt; x;         cerr &lt;&lt; x &lt;&lt; endl;     }      return 0; }   input.txt:  10   20   30   Output:  10   20   30   30   Note: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).
11109
I've been having a lot of problems trying to figure out how to use scanf().  It seems to work fine with integers, being fairly straight forward scanf("%d", &amp;i).  Where I am running into issues is using scanf() in loops trying to read input.  For example:  do {   printf("counter: %d: ", counter);   scanf("%c %c%d", &amp;command, &amp;prefix, &amp;input); } while (command != 'q');    When I enter in a validly structured input like c P101, it seems to loop again before prompting me.  This seems to happen even with a single:  scanf("%c", &amp;c)    in a while loop.  It'll do the loop twice before prompting me again.  What is making it loop twice, and how do I stop it? When I enter in less amount of input that programmatically wouldn't have another character or number such as q, pressing enter seems to prompt me to enter more.  How do I get scanf() to process both single and double character entries?
10153
Suppose that I have a file called temp.txt.  Using the cat program, I would like to add the contents of this file to the end of myfile.txt -- creating myfile.txt if it does not exist and appending to it if it does.    I am considering these possibilities:  cat temp.txt &gt; myfile.txt   or  cat temp.txt &gt;&gt; myfile.txt   Both commands appear to work as I want.  So, my question is, what is the difference between &gt; and &gt;&gt;?  Thanks for your time.
34476
With reference to the following thread:   What is the best way to programatically determine the correct charset encoding of an inputstream/file ?  I have tried using the following:  File in =  new File(args[0]); InputStreamReader r = new InputStreamReader(new FileInputStream(in)); System.out.println(r.getEncoding());   But on a file which I know to be encoded with ISO8859_1 the above code yields ASCII, which is not correct, and does not allow me to correctly render the content of the file back to the console.
6617
I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.  What is the best way to do this, within the following code?  f = open(file) for line in f:     if line.contains('foo'):         newline = line.replace('foo', 'bar')         # how to write this newline back to the file