你好:) 我需要有人将这个小 bash 脚本翻译成 C,因为现在它消耗大量 CPU,这样我(和其他在 google 上搜索这个的人)就可以学习用 C 走路!这对于学习和我计划用 C 做很多事情是最有效的,但我只是一个脚本语言程序员并且了解非常基本的 java....
*BASH SCRIPT TO TRANSLASTE TO C*
a1=$1
a2=`expr $a1 + 1`
a3=`expr $a1 + 2`
a4=`expr $a1 + 3`
a5=`expr $a1 + 4`
Limit=`expr $a1 + 99999999999`
while [ $a1 -le $Limit ]
do
echo $a1,$a2,$a3,$a4,$a5 | sed 's/9,/9abc/g' >> List$1
a1=`expr $a1 + 500`
a2=`expr $a2 + 500`
a3=`expr $a3 + 500`
a4=`expr $a4 + 500`
a5=`expr $a5 + 500`
done
..因此,如果我知道 C 语言中的以下内容,那么现在就全部了。
- 处理变量
- 相当于 >> 添加到文件,但最好带有缓存 减少磁盘io!
- 与 $1 等价的东西 - 允许用户设置变量 当运行C程序时。
- C 中的正则表达式
- 相当于 | C 中的管道
- 或者如何在 C 程序中执行 bash 命令,因为它 无论如何,不能比 grep、sed 快得多...
非常感谢大家阅读本文
最佳答案
类似这样的事情:
#ifdef __cplusplus
#include <cstdio>
#include <cstdlib>
#include <cstring>
#else
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#endif
char * stringReplace(char *string, char *search, char *replace)
{
char *tempString, *searchStart;
int len=0;
// preuefe ob Such-String vorhanden ist
searchStart = strstr(string, search);
if(searchStart == NULL) {
return string;
}
// Speicher reservieren
tempString = (char*) malloc(strlen(string) * sizeof(char));
if(tempString == NULL) {
return NULL;
}
// temporaere Kopie anlegen
strcpy(tempString, string);
// ersten Abschnitt in String setzen
len = searchStart - string;
string[len] = '\0';
// zweiten Abschnitt anhaengen
strcat(string, replace);
// dritten Abschnitt anhaengen
len += strlen(search);
strcat(string, (char*)tempString+len);
// Speicher freigeben
free(tempString);
return string;
}
int main(int argc, char* argv[])
{
int i;
for(i = 0; i < argc; ++i)
printf("argv[%d]: %s\n", i, argv[i]);
char string [256];
int a1 = atoi((const char*) gets(string));
int a2= a1 +1;
int a3 = a1 + 2;
int a4 = a1 + 3;
int a5 = a1 + 4;
int limit = a1 + 99999999999;
while(a1 <= limit)
{
char command[1000];
sprintf(command, "%d,%d,%d,%d,%d", a1, a2, a3, a4, a5);
stringReplace(command, "9,", "9abc");
FILE* pFile = fopen ("myfile.txt","wa");
fprintf (pFile, "%s\n", command);
fclose (pFile);
/*
sprintf(command, "echo \"%d,%d,%d,%d,%d\" | sed 's/9,/9abc/g' >> List%s", a1, a2, a3, a4, a5, string);
FILE* pPipe = popen(command, "r");
char psBuffer[128];
while( !feof( pPipe ) )
{
if( fgets( psBuffer, 128, pPipe ) != NULL )
printf("%s\n", psBuffer );
}
pclose(pPipe);
*/
a1 += 500;
a2 += 500;
a3 += 500;
a4 += 500;
a5 += 500;
}
return EXIT_SUCCESS;
}
关于c - 学习用 C 语言行走 - 将 5 行 bash shell 脚本翻译为 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5719554/