提交 766ba5cc 创建 作者: rsc's avatar rsc

first ever correct use of strncpy

上级 aa6824ab
...@@ -127,6 +127,7 @@ void* memset(void*, int, uint); ...@@ -127,6 +127,7 @@ void* memset(void*, int, uint);
char* safestrcpy(char*, const char*, int); char* safestrcpy(char*, const char*, int);
int strlen(const char*); int strlen(const char*);
int strncmp(const char*, const char*, uint); int strncmp(const char*, const char*, uint);
char* strncpy(char*, const char*, int);
// syscall.c // syscall.c
int argint(int, int*); int argint(int, int*);
......
...@@ -455,15 +455,7 @@ writei(struct inode *ip, char *src, uint off, uint n) ...@@ -455,15 +455,7 @@ writei(struct inode *ip, char *src, uint off, uint n)
int int
namecmp(const char *s, const char *t) namecmp(const char *s, const char *t)
{ {
int i; return strncmp(s, t, DIRSIZ);
for(i=0; i<DIRSIZ; i++){
if(s[i] != t[i])
return s[i] - t[i];
if(s[i] == 0)
break;
}
return 0;
} }
// Look for a directory entry in a directory. // Look for a directory entry in a directory.
...@@ -500,18 +492,6 @@ dirlookup(struct inode *dp, char *name, uint *poff) ...@@ -500,18 +492,6 @@ dirlookup(struct inode *dp, char *name, uint *poff)
return 0; return 0;
} }
// Copy one name to another.
static void
namecpy(char *s, const char *t)
{
int i;
for(i=0; i<DIRSIZ && t[i]; i++)
s[i] = t[i];
for(; i<DIRSIZ; i++)
s[i] = 0;
}
// Write a new directory entry (name, ino) into the directory dp. // Write a new directory entry (name, ino) into the directory dp.
int int
dirlink(struct inode *dp, char *name, uint ino) dirlink(struct inode *dp, char *name, uint ino)
...@@ -534,7 +514,7 @@ dirlink(struct inode *dp, char *name, uint ino) ...@@ -534,7 +514,7 @@ dirlink(struct inode *dp, char *name, uint ino)
break; break;
} }
namecpy(de.name, name); strncpy(de.name, name, DIRSIZ);
de.inum = ino; de.inum = ino;
if(writei(dp, (char*)&de, off, sizeof(de)) != sizeof(de)) if(writei(dp, (char*)&de, off, sizeof(de)) != sizeof(de))
panic("dirwrite"); panic("dirwrite");
......
...@@ -56,8 +56,20 @@ strncmp(const char *p, const char *q, uint n) ...@@ -56,8 +56,20 @@ strncmp(const char *p, const char *q, uint n)
n--, p++, q++; n--, p++, q++;
if(n == 0) if(n == 0)
return 0; return 0;
else return (uchar)*p - (uchar)*q;
return (int) ((uchar) *p - (uchar) *q); }
char*
strncpy(char *s, const char *t, int n)
{
char *os;
os = s;
while(n-- > 0 && (*s++ = *t++) != 0)
;
while(n-- > 0)
*s++ = 0;
return os;
} }
// Like strncpy but guaranteed to NUL-terminate. // Like strncpy but guaranteed to NUL-terminate.
......
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论