Reading Files on CUDA Using Visual Studio 2005

void main()
//long for reading file size
long lSize = 0;
FILE *f = fopen( “C:/Documents and Settings/Administrator/Desktop/Small.txt”, “rb” );

  // reading file size
  fseek (f , 0 , SEEK_END);
  lSize = ftell (f);
  rewind (f);
  //copying file content to array ibuffer
  char * ibuffer = new char[lSize];
  fread( ibuffer, lSize, 1, f );
  //for (int i =0; i < lSize; i++)
  //printf("%c", ibuffer[i]);
  fclose( f );

  char *a_h, *a_d;  // Pointer to host & device arrays

  a_h = (char *)malloc(lSize);        // Allocate array on host

  cudaMalloc((void **) &a_d, lSize);   // Allocate array on device

  // Initialize host array and copy it to CUDA device

  for (int i=0; i<lSize; i++)
            a_h[i] = ibuffer[i];

  cudaMemcpy(a_d, a_h, lSize, cudaMemcpyHostToDevice);

  // Retrieve result from device and store it in host array

  cudaMemcpy(a_h, a_d, sizeof(char)*lSize, cudaMemcpyDeviceToHost);

  //Print results

  for (int i=0; i<lSize; i++) 
            printf("%c", a_h[i]);

  // Cleanup

  free(a_h); cudaFree(a_d);


// Please tell me what you think about the code and don’t hesitate in pointing out the bad parts.
// Thanking you all in advance :thumbup:

I really don’t understand your target, I think that your code and your topic title is not coincide.

before read your code, I think that you directly open and read file to device global memory,

but in your case

read file to host memory -> copy to device memory -> do some thing->return to host memory.

is it right?


My intention was to show the people out there how they can read files, copy them to an array using memcpy on the device, if they want send the array to a function, and then copy it back to the host and printing the content. What I am looking for in the response, is a critique to the way I did it and if it can be improved, or if reading of files can be done in any other way. :rolleyes: … Is there a way you can open and read file to device global memory directly??? :unsure:

I tried, but I unsuccessful.

If anyone else can do, It will be very interesting?


thanks 4 ur effort :thumbup:

How are able to FILE * variable? What library file r u using? Becos CUDA does not accept fstream, iostream