App下載

C語言中%*s中*是什么作用?

猿友 2021-02-01 17:37:17 瀏覽數(shù) (11627)
反饋

取決于在 ?scanf? 中使用還是在 ?printf? 中使用。

  1. 在 ?scanf? 中使用,則添加了?*?的部分會被忽略,不會被參數(shù)獲取。例如:
    int a,b;char b[10];
    scanf("%d%*s",&a,b);
    輸入為:?12 abc? 那么?12?將會讀取到變量 ?a? 中,但是后面的 ?abc? 將在讀取之后拋棄,不賦予任何變量(例如這里的字符數(shù)組?b?)
  2. 在? printf? 中使用,表示用后面的形參替代的位置,實現(xiàn)動態(tài)格式輸出。例如:
    printf("%s", 10, s);
    /意思是輸出字符串 s,但至少占10個位置,不足的在字符串s左邊補空格,這里等同于 printf("%10s", s);*/
  3. 在舉個例子,假如要打印 linux 根文件系統(tǒng)下的? /proc/x/status? 中的第一行 “?Name: login?”,如下
[root@sz /proc/898]#cat status 
Name:   login
State:  S (sleeping)
Tgid:   898
Pid:    898
PPid:   519
TracerPid:      0
Uid:    0       0       0       0
Gid:    0       0       0       0
FDSize: 32
Groups:
VmPeak:     1232 kB
VmSize:     1232 kB
VmLck:         0 kB
VmPin:         0 kB
VmHWM:       312 kB
VmRSS:       312 kB
VmData:       64 kB
VmStk:       136 kB
VmExe:       708 kB
VmLib:       312 kB
VmPTE:         8 kB
VmSwap:        0 kB
Threads:        1
SigQ:   0/469
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000000002000
CapInh: 0000000000000000
CapPrm: 0000001fffffffff
CapEff: 0000001fffffffff
CapBnd: 0000001fffffffff
Cpus_allowed:   1
Cpus_allowed_list:      0
Mems_allowed:   1
Mems_allowed_list:      0
voluntary_ctxt_switches:        1
nonvoluntary_ctxt_switches:     2

為了只獲取 “?Name: login?”中的 ?login?,可以采用如下

//描述: 線程是否存在
//返回: 成功表示存在,返回true,反之為false。
bool IsThreadExist(char *task_name)
 {
     DIR *dir;
     struct dirent *ptr;
     FILE *fp;
     char filepath[50];
     char cur_task_name[50];
     char buf[BUF_SIZE];
     bool fRet = false;
     dir = opendir("/proc"); 
     if (NULL != dir)
     {
         while ((ptr = readdir(dir)) != NULL)
         {
             if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0))
                 continue;
             if (DT_DIR != ptr->d_type)
                 continue;
             sprintf(filepath, "/proc/%s/status", ptr->d_name);
             fp = fopen(filepath, "r");
             if (NULL != fp)
             {
                 if( fgets(buf, BUF_SIZE-1, fp)== NULL ){
                     fclose(fp);
                     continue;
                 }
                 sscanf(buf, "%*s %s", cur_task_name);
                 if (strcmp(task_name, cur_task_name) == 0){
                     fRet = true;
                 }
                 fclose(fp);
             }
         }
         closedir(dir);
     }
     return fRet;
 }


C C++ C#

0 人點贊