我嘗試解析以下格式的行:使用strtok()
功能與2個分隔符和
,
(空格和逗號)的strtok()返回NULL
1: 2,3,4,5,6,7,8,9,10
因此Im 但由於某些原因,當我到6 funcion返回NULL。
fileName = strtok(line, spaceToken);
fileName[strlen(fileName) - 1] = 0; //remove the ':'
...
//doing something with fileName
...
fileName = strtok(NULL, commaToken);
while (fileName != NULL) <-----THE PROBLEM
...
//doing something with fileName
fileName = strtok(NULL, commaToken);
}
因此當文件名應爲6
,我得到NULL
。
有了這個輸入:
file1: file2,file3,file4
我在哪裏得到前人的精力爲file2
的fileName
我越來越'fil'
,而下一次迭代將NULL
。
這是完整的代碼,如果它是幫助
#include <stdio.h>
#include <memory.h>
#define MAX_LINE_NUMBER 11
#define MAX_FILE_NAME_NUMER 255
#define MAX_FILES 10
//function declaration
void parseFile(char path[]);
int contain(char fileName[]);
int addToDependencieArray(char fileName[], int currentFileIndex);
enum COLOR
{
WHITE, GRAY, BLACK
};
typedef struct MyFile
{
char name[MAX_FILE_NAME_NUMER];
int neighbors[MAX_FILES];
int neighborsCounter;
enum COLOR myColor;
int predecessor;
} MyFile;
//global
MyFile gDependencies[MAX_FILES];
int gCurrentFilesWriten = 0;
int main(int argc, char *argv[])
{
parseFile(argv[1]);
puts("hello");
}
void parseFile(char path[])
{
FILE *fPointer = fopen(path, "r");
char line[MAX_LINE_NUMBER];
char spaceToken[2] = " ";
char commaToken[2] = ",";
char *fileName;
int currentFileIndex = 0;
int sourseFile = 0;
while (fgets(line, sizeof(line), fPointer))
{
fileName = strtok(line, spaceToken);
fileName[strlen(fileName) - 1] = 0; //remove the :
int sourse = contain(fileName);
if (sourse == -1) // isn't contains
{// to create function add.
currentFileIndex = addToDependencieArray(fileName, currentFileIndex);
sourseFile = currentFileIndex - 1;
}
else // contain
{
sourseFile = sourse;
}
fileName = strtok(NULL, commaToken);
while (fileName != NULL)
{
if (contain(fileName) == -1)
{
currentFileIndex = addToDependencieArray(fileName, currentFileIndex);
int neighborIndex = gDependencies[sourseFile].neighborsCounter;
gDependencies[sourseFile].neighbors[neighborIndex] = currentFileIndex - 1;
gDependencies[sourseFile].neighborsCounter++;
}
fileName = strtok(NULL, commaToken);
}
}
fclose(fPointer);
}
int contain(char fileName[])
{
int res = -1;
for (int i = 0; i < gCurrentFilesWriten; i++)
{
if (!strcmp(fileName, gDependencies[i].name))
{
return i;
}
else
{
i++;
}
}
return res;
}
int addToDependencieArray(char fileName[], int currentFileIndex)
{
strcpy(gDependencies[currentFileIndex].name, fileName);
gCurrentFilesWriten++;
gDependencies[currentFileIndex].neighborsCounter = 0;
currentFileIndex++;
return currentFileIndex;
}
'文件名[strlen的( fileName) - 1] = 0;'注意:strlen()可以返回零。 (在這種情況下文件名甚至可以是NULL) – joop
謝謝,但我可以假設不會有任何空行。 – limitless
爲什麼不用硬編碼的數據寫一個小的主程序,而不是假設事情是「好的」? – PaulMcKenzie