How do I read from file in CUDA? fstream doesn't load/work properly...

Hey Everyone,

I’ve been working on a project with CUDA and ran into a problem. I’m trying to load my data from a text file and using fstream doesn’t seem to work with CUDA.

Even adding just "#include " in a CUDA code, it gives me 80 some compilation errors. I’ve copied the include files into the CUDA includes, checked my environment paths and yet nothing is working.

When I was searching on google, I also came across a built-in CUDA function “cutReadFilef” (i think that’s how it’s spelled) which also reads from a file. But all my code is already written with fstreams and it would be easier to just get that to work.

So, if anyone knows how to use fstream in CUDA or read from files, please help me. Your assistance is greatly appreciated.


NVCC compiler currently supports C with some additions (such as templates), so that’s the reason you’re unable to use fstream (there are a few other threads that discussed C++ compatibility).

In the meantime, you can use C++ in CUDA projects, just don’t mix the two in the same file. So, you can have kernels in a .cu file, which is compiled by NVCC. You can have I/O code in a .cpp file, which is compiled by your C++ compiler. The code in .cpp file can call C-style functions in the .cu file, just make sure that those functions are declared as extern “C”. That way you can reuse all your existing code and pass data to C-style functions that in turn call the corresponding CUDA kernels.


Thanks for the reply, it works!

Just as an addition: you can also guard the code that should only be compiled by MS Visual C++ by preprocessor defines in the .cu file:

#if defined(_MSC_VER)



This makes it possible to mix code that has to be compiled by nvcc and code that has to be compiled by MSVC in one .cu file as _MSC_VER is only defined by the MSVC compiler. Nvcc simply ignores the code within such a block, but passes it on to the MSCV compiler which in return compiles the nvcc-generated code as well as these previously excluded blocks.

The same should work for gcc on the linux platform. The only difference should be that you must check if GNUC is defined (not really sure if this is working as I’ve only tested it on MS Windows).