Thursday, 15 July 2010

Reading and writing files in c -


I want to know that my program is mine. It reads them but I can not manage to input them into an array for later use. Can someone help me understand the better way to read and write files in C, please let me know on this subject , I know that I want to use int instead of chimes because my .txt file has only numbers but for functions like fast, I think for characters only.

  #include & lt; Stdio.h & gt; Int main () {FILE * file; Four names [10] = "100.txt"; Four lines [10]; Int n; Four mothers [5]; File = FOPN (name, "RT"); If (file == NULL) {printf ("There is no such file! \ N"); Return 0; } For (n = 0; n & lt; 100; n ++) {fgets (line, 5, file); // put (line); I [n] = line; puts in]); } Fclose (file); Return 0; }  

If you switch to fscanf, then using int instead of char , And you're parsing a text file that has numbers, which makes it more understandable. Assume that your 100.txt contains 100 numbers different from a white space, it should work:

  int main (int argc, char * argv []) {FILE * file; Four names [10] = "100.txt"; Four lines [10]; Int n; Int numbers are [100]; File = FOPN (name, "RT"); If (file == NULL) {printf ("There is no such file! \ N"); Return 0; } For (n = 0; n & lt; 100; n ++) {fscanf (file, "% d", and numbers around [n]); } Fclose (file); Return 0; }  

Here is a link to an explanation.

Edit:

  is another, more elegant solution to use while (fscanf (file, "% d "& Amp; numbers are [n ++]) == 1);  

In this way, you should be careful in the form of a number of loops (ie programmed by ) through your text file. If the count of numbers in the text file is more than the allocated space for the array.

To write back to a file:

  FILE * fp = fopen ("out_file. Txt "," w "); // int arrNumSize = open the file to write sizeof (numberArray) / sizeof (int); for (int i = 0; i & lt; arrNumSize; i ++) {FPF , "% D", number too [I]);} Fclose (fpose);  

No comments:

Post a Comment