code_junkie

Unexpected output copying file in C

Nov 13th, 2011
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. inputFile = fopen("D:\input.txt", "r");
  2. outputFile = fopen("D:\output.txt", "w");
  3.  
  4. if(inputFile)
  5. {
  6. //Get size of inputFile
  7. fseek(inputFile, 0, SEEK_END);
  8. inputFileLength = ftell(inputFile);
  9. fseek(inputFile, 0, SEEK_SET);
  10.  
  11. //Allocate memory for inputBuffer
  12. inputBuffer = malloc(inputFileLength);
  13.  
  14. if(inputBuffer)
  15. {
  16. fread (inputBuffer, 1, inputFileLength, inputFile);
  17. }
  18.  
  19. fclose(inputFile);
  20.  
  21. if(inputBuffer)
  22. {
  23. fprintf(outputFile, "%s", inputBuffer);
  24. }
  25.  
  26. //Cleanup
  27. free(inputBuffer);
  28. fclose(outputFile);
  29. }
  30.  
  31. int numBytesRead = 0;
  32. if(inputBuffer)
  33. {
  34. numBytesRead = fread (inputBuffer, 1, inputFileLength, inputFile);
  35. }
  36.  
  37. fclose(inputFile);
  38.  
  39. if(inputBuffer)
  40. {
  41. fwrite( inputBuffer, 1, numBytesRead, outputFile );
  42. }
  43.  
  44. FILE *fin = fopen ("infile","rb"); // make sure you check these for NULL return
  45. FILE *fout = fopen ("outfile","wb");
  46. char buff[1000000]; // or malloc/check-null if you don't have much stack space.
  47. while ((count = fread (buff, 1, sizeof(buff), fin)) > 0) {
  48. // Check count == -1 and errno here.
  49. fwrite (buff, 1, count, fout); // and check return value.
  50. }
  51. fclose (fout);
  52. fclose (fin);
  53.  
  54. fwrite (inputBuffer , 1 , inputFileLength , outputFile );
Add Comment
Please, Sign In to add comment