我对论坛很新,所以我希望我不要搞砸。 我有一个从文件中读取的程序,到目前为止它将文件放入2D char数组中。我现在需要strtok 2D'字符串'并将每个部分放入结构
这是代码
struct processes
{
char processNumber[20];
int quanta;
int priority;
}process;
和
int readSave(int argc, char ** argv)
{
int i,j,k,count;
size_t blocksize = 16;
char originalFile[256], newFile[1000][20];
int fileDes;
ssize_t status;
unsigned char buffer[blocksize];
strcpy(originalFile, argv[1]);
fileDes = open(originalFile, O_RDONLY); // open for reading
i=0;
status = 99;
while(status > 0 ) // while no error
{
status = read(fileDes, buffer, blocksize);
strcpy(newFile[i],buffer); //line 71
for(k = 0; k <= blocksize; k++)
{
buffer[k] = 0;
}
i++;
if(status < 0)
{
printf("\nERROR\n");
exit(6);
}
}
//remove later
for(j = 0; j < i; j++) // prints out string to make sure it was input properly
{
printf("%s", newFile[j]);
}
printf("\n");
close(fileDes);
//Don't know how to carry on
}
我希望你能帮到我,因为我迷路了 编辑 struct processStruct processes [7000]; while(newFile!= NULL) { strcpy(processes [count] .processNumber,strtok(newFile [count],“\ n”)); processes [count] .quanta = atoi(strtok(NULL,“\ n”)); processes [count] .priority = atoi(strtok(NULL,“\ n”));
count ++;
}
我更改了@Igor给出的结构和输入但是当我运行它时,我得到了一个分段错误,当我用-Wall编译时,我得到了 readtostring.c:在函数'readSave'中: readtostring.c:71:3:警告:传递参数2的'strcpy'中的指针目标在签名方面有所不同[-Wpointer-sign] /usr/include/string.h:128:14:注意:预期'const char * restrict '但参数类型为'unsigned char *'
答案 0 :(得分:1)
问题1:
好像你应该strtok(newFile[something], " \n")
而不是strtok(newFile, " \n")
。
并且不要忘记在每次迭代中执行something++
。
问题2:
您不能strcpy
到int
。请尝试改为:
process[something].quanta = atoi(strtok(NULL, " \n"));
process[something].priority = atoi(strtok(NULL, " \n"));
问题3:
process
是结构而不是结构数组,因此您无法执行process[something]
。你的意思是创建一个结构数组:processes process[20];