伙计们,我想从我的文件中读取文本,并将每个字符分配给数组的单个元素
__global__ void setup_cuRand(curandState * state, unsigned long seed)
{
int id = threadIdx.x;
curand_init(seed, id, 0, &state[id]);
}
__global__ void poblar(int * adn, curandState * state){
curandState localState = state[threadIdx.x];
int random = curand(&localState);
adn[threadIdx.x] = random;
// It doesn't mind if i use the following instruction, the result is a lot of 0's
//adn[threadIdx.x] = threadIdx.x;
}
int main()
{
const int adnLength = NUMCROMOSOMAS * SIZECROMOSOMAS; // 256 * 128 (32.768)
const size_t adnSize = adnLength * sizeof(int);
int adnCPU[adnLength];
int * adnDevice;
cudaError_t error = cudaSetDevice(0);
if (error != cudaSuccess)
exit(-EXIT_FAILURE);
curandState * randState;
error = cudaMalloc(&randState, adnLength * sizeof(curandState));
if (error != cudaSuccess){
cudaFree(randState);
exit(-EXIT_FAILURE);
}
//Here is initialized cuRand
setup_cuRand <<<1, adnLength >> > (randState, unsigned(time(NULL)));
error = cudaMalloc((void **)&adnDevice, adnSize);
if (error == cudaErrorMemoryAllocation){// cudaSuccess){
cudaFree(adnDevice);
cudaFree(randState);
printf("\n error");
exit(-EXIT_FAILURE);
}
poblar <<<1, adnLength >>> (adnDevice, randState);
error = cudaMemcpy(adnCPU, adnDevice, adnSize, cudaMemcpyDeviceToHost);
//After here, for any i, adnCPU[i] is 0 and i cannot figure what is wrong
if (error == cudaSuccess){
for (int i = 0; i < NUMCROMOSOMAS; i++){
for (int j = 0; j < SIZECROMOSOMAS; j++){
printf("%i,", adnCPU[(i*SIZECROMOSOMAS) + j]);
}
printf("\n");
}
}
return 0;
}
但问题是输出是一些奇怪的符号而不是文件的文本是&#34;这只是一个测试&#34;。为什么会发生这种情况?
答案 0 :(得分:5)
可能的原因包括:
fopen
无法打开指定的文件。通过检查i
。int i = 0, j = 0;
char A[1000];
FILE* fpointer;
fpointer = fopen("text.txt", "r");
if(!fpointer)
{
fputs("fopen failed! Exiting...\n", stderr);
exit(-1); /* Requires `stdlib.h` */
}
while(fscanf(fpointer, "%c", &A[i]) != EOF)
{
i = i + 1;
}
fclose(fpointer);
for (j = 0; j < i; j++){
printf("A[%d] = '%c'\n", j, A[j]);
}
的所有内容进行修复。更正了代码段:
{{1}}
答案 1 :(得分:1)
如果您的文件不包含null character,则可以避免使用其他变量来存储读取的字符数。如果null终止读入的字符,则可以直接将它们打印为字符串。
您必须确保A可以容纳足够的字符。如果您预计最多1000个字符,请确保A的大小为1001字节以包含终止NUL字符。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char A[1001] = { 0 }; /* init to NUL, expect at most 1000 chars */
int i;
FILE *fpointer;
fpointer=fopen("text.txt","r");
if(!fpointer) {
perror("Error opening file"); /* print error message */
exit(-1); /* Requires `stdlib.h` */
}
/* read all characters from fpointer into A */
for (i=0; fscanf(fpointer, "%c", &A[i]) != EOF; i++);
fclose(fpointer);
printf("%s\n",A); /* print all characters as a string */
/* alternatively, loop until NUL found */
for (i=0; A[i]; i++)
printf("%c", A[i]);
printf("\n");
return 0;
}