我想在我的C程序中操作ls -al命令的输出。 有办法吗?
int main()
{
int return_value;
return_value = system("ls -al ");
return return_value;
}
答案 0 :(得分:2)
你需要一个管道来处理这个过程。
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char output[1024];
fp = popen("/bin/ls -al", "r");
if (fp == NULL)
exit(1);
while (fgets(output, 1023, fp) != NULL)
printf("%s", output);
pclose(fp);
return 0;
}
答案 1 :(得分:1)
您可以使用session_start();
if($_SERVER['REQUEST_METHOD']=='POST' && !empty($_POST['submit'])) {
$uname = $_POST['uname'];
$pw = $_POST['pw'];
require_once('db.php');
//Checking whether the cookies are set or not
if(!empty($_COOKIES['Last_Login_UserID']) && !empty($_COOKIES['Last_Login_Password'])){
if($_COOKIES['Last_Login_UserID']==$uname && $_COOKIES['Last_Login_Password']==$pw){
//Cookies are perfect give access
$_SESSION['username'] = $uname;
$_SESSION['password'] = $pw;
header('Location: products_list.php');
}else{
//Cookies cookies are wrong
login_check($uname,$pw);
}
}else{
//Cookies are not set so check the database
login_check($uname,$pw);
}
//Function to check the login
function login_check($uname,$pw){
$sql = 'SELECT * FROM users_table WHERE username="'.mysql_escape_string($uname).'" AND password="'.mysql_escape_string(md5($pw)).'" LIMIT 0, 1 ;';
$qry = mysql_query($sql);
$count = mysql_num_rows($qry);
if($count == 1) {
$_SESSION['username'] = $uname;
$_SESSION['password'] = $pw;
if(!empty($_POST['remember_me']) && $_POST['remember_me']==true){
setcookie('Last_Login_UserID',$_SESSION['username'],(60*60*24),"/");
setcookie('Last_Login_Password',$_SESSION['password'],(60*60*24),"/");
}
header('Location: products_list.php');
} else {
header('Location: index.php?error=1');
}
}}
上的popen(3)作为answered作为Baris Demiray。
但是在您的特定情况下(将文件放在目录中),您实际上不需要启动运行/bin/ls
的外部流程,您只需使用opendir(3)&amp; readdir(3)读取目录条目,并在每个条目上使用stat(2)(您将使用snprintf(3)构建路径)。另请参阅glob(7),nftw(3)并阅读Advanced Linux Programming
请注意,system(3)是一个命名很差的standard C library函数。它不是直接的system call(它们列在syscalls(2) ...中),而是使用fork(2),execve(2),waitpid(2)等... < / p>