Learning to walk with C - translating a 5 lines bashshell script to C [closed]
Hello:) I need someone to t开发者_StackOverflow社区ranslate this little bash script to C because now it consumes way to much CPU and so that i (and other people searching this on google) can learn walking with C! This will be most effective to learn and im planing to do a lot with C but yet iam a programmer of script languages only and know very basic 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
..Thus if i knew the following things in C this would be all for now.
- handleing the variables
- euivalent for >> adding to file but perferably with a cache to reduce disk io!
- something euivalent to $1 - allowing the user to set a variable when running the C programm.
- REGEX in C
- euivalent to | pipe in C
- Or how to execute a bash command within a C programm since it cant get much faster than grep,sed anyways...
Thanks a lot to everyone reading this
Something like this:
#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;
}
精彩评论