当我运行此程序时。文件描述符返回-1
值,因此程序终止。我不知道为什么会这样。由于pid值正是我要打开的文件的名称。
const char *psyn = "product/productId:";
char line[100];
pFile = fopen ("pids.txt" , "r");
if (pFile == NULL) perror ("Error opening file");
else {
while(fgets (line , sizeof(line) , pFile))
{
if (strstr(line, psyn) == line)
{
leng = strlen(line);
if( line[leng-1] == '\n' )
line[leng-1] = 0;
if( line[0] == '\n' )
line[0] = 0;
pid = line+strlen(psyn)+1;
strcat(pid,t);
leng = strlen(pid);
if( pid[leng-1] == '\n' )
pid[leng-1] = 0;
fd = open(pid, O_RDWR, 0644);
if (fd == -1)
cout<<"eror in file \n";
else { //.. rest of the program}
答案 0 :(得分:0)
pid = line+strlen(psyn)+1;引起了我的怀疑。这里的第一个strlen()效率不高。其次,+1比字符串长一个。
int opt_verbose; // from -v option char psyn[] = "product/productId:"; // array, not pointer char line[100]; FILE *pFile = fopen ("pids.txt" , "r"); if (pFile == NULL) perror ("Error opening file"); else { while(fgets (line , sizeof(line) , pFile)) { char *s = strstr(line, psyn); if ( s == line) { int leng; for ( leng = strlen(line); leng > 0 && isspace(line[leng-1]); leng-- ) line[leng-1] = '\0'; char *pid = line + sizeof(psyn) - 1; // sizeof without \0 strcat(pid,t); leng = strlen(pid); if( pid[leng-1] == '\n' ) pid[leng-1] = 0; if ( opt_verbose ) printf( "VERBOSE: opening %s\n", pid ); int fd = open(pid, O_RDWR, 0644); if (fd == -1) { // perror is usually not sufficiently detailed printf( "ERROR: open \"%s\" failed: (%d) %s\n", pid, errno, strerror(errno) ); // \"%s\" nicely shows unexpected spaces in paths. continue; }