Search Results

Search found 1221 results on 49 pages for 'argv'.

Page 5/49 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • C string question

    - by user208454
    I am writing a simple c program which reverses a string, taking the string from argv[1]. Here is the code: #include <stdio.h> #include <stdlib.h> #include <string.h> char* flip_string(char *string){ int i = strlen(string); int j = 0; // Doesn't really matter all I wanted was the same size string for temp. char* temp = string; puts("This is the original string"); puts(string); puts("This is the \"temp\" string"); puts(temp); for(i; i>=0; i--){ temp[j] = string[i] if (j <= strlen(string)) { j++; } } return(temp); } int main(int argc, char *argv[]){ puts(flip_string(argv[1])); printf("This is the end of the program\n"); } That's basically it, the program compiles and everything but does not return the temp string in the end (just blank space). In the beginning it prints temp fine when its equal to string. Furthermore if I do a character by character printf of temp in the for loop the correct temp string in printed i.e. string - reversed. just when I try to print it to standard out (after the for loop/ or in the main) nothing happens only blank space is printed.

    Read the article

  • Defining a function that is both a generator and recursive [on hold]

    - by user96454
    I am new to python, so this code might not necessarily be clean, it's just for learning purposes. I had the idea of writing this function that would display the tree down the specified path. Then, i added the global variable number_of_py to count how many python files were in that tree. That worked as well. Finally, i decided to turn the whole thing into a generator, but the recursion breaks. My understanding of generators is that once next() is called python just executes the body of the function and "yields" a value until we hit the end of the body. Can someone explain why this doesn't work? Thanks. import os from sys import argv script, path = argv number_of_py = 0 lines_of_code = 0 def list_files(directory, key=''): global number_of_py files = os.listdir(directory) for f in files: real_path = os.path.join(directory, f) if os.path.isdir(real_path): list_files(real_path, key=key+' ') else: if real_path.split('.')[-1] == 'py': number_of_py += 1 with open(real_path) as g: yield len(g.read()) print key+real_path for i in list_files(argv[1]): lines_of_code += i print 'total number of lines of code: %d' % lines_of_code print 'total number of py files: %d' % number_of_py

    Read the article

  • C++ classes & linked list: adding & counting items

    - by user342289
    I need to make a linked list with classes. Each list will store two values: a URI and IP. After doing all the adding, I need to be able count the total number of items in the linked list. I have tried the following code but it doesn't compile. Any suggestions please? #include <iostream> #include <cstdlib> #include <string> using namespace std; class ip_uri_store { protected: string ip; string uri; ip_uri_store *next; public: ip_uri_store(string huri, string hip); void additem(string auri, string aip); void deleteitem(string duri); void findbyuri(string furi); void findbyip(string fip); int totalitems(); }; ip_uri_store *head = NULL; ip_uri_store *curr = NULL; void ip_uri_store::additem(string auri, string aip) { curr = head; while (curr->next != NULL) { curr = curr->next; } curr->uri = auri; curr->next = new ip_uri_store; curr->ip = aip; curr->next = new ip_uri_store; curr = curr->next; curr = head; } int ip_uri_store::totalitems() { int i = 0; curr = head; while (curr->next != NULL) { i += 1; curr = curr->next; } return i; } int main(int argc, char *argv[]) { if (argc == 1) { cout << "123456, [email protected], Gordon Brown" << endl; return (0); } head = new ip_uri_store; curr = head; int i; for (i = 1; i < argc; i++) { if (argv[i][0] == 'A') //add item { ip_uri_store.additem(argv[i + 1], argv[i + 2]); i += 2; } else if (argv[i][0] == 'N') //print total tiems { cout << ip_uri_store.totalitems() << endl; } else { cout << "command error\n"; return 0; } } return (0); }

    Read the article

  • Perl regex matching output from `w -hs` command

    - by Bushman
    I'm trying to write a Perl script that will work better with KDE's kwrited, which, as far as I can tell, is connected to a pts and puts every line it receives through the KDE system tray notifications, with the title "KDE write daemon". Unfortunately, it makes a separate notification for each and every line, so it spams up the system tray with multiline messages on regular old write, and for some reason it cuts off the entire last line of the message when using wall (One-line messages are also goners.). I was also hoping to make it so that it could broadcast across a LAN with thick clients. Before starting on that (which would require ssh, of course), I tried to make an ssh-less version to make sure it works. Unfortunately, it doesn't. perl ./write.pl "Testing 1 2 3" where the following is the contents of ./write.pl: #!/usr/bin/perl use strict; use warnings; my $message = ""; my $device = ""; my $possibledevice = '`w -hs | grep "/usr/bin/kwrited"`'; #Where is kwrited? $possibledevice =~ s/^[^\t][\t]//; $possibledevice =~ s/[\t][^\t][\t ]\/usr\/bin\/kwrited$//; $possibledevice = '/dev/'.$possibledevice; unless ($possibledevice eq "") { $device = $possibledevice; } if ($ARGV[0] ne "") { $message = $ARGV[0]; $device = $ARGV[1]; } else { $device = $ARGV[0] unless $ARGV[0] eq ""; while (<STDIN>) { chomp; $message .= <STDIN>; } } if ($message ne "") { system "echo \'$message\' > $device"; } else { print "Error: empty message" } produces the following error: $ perl write.pl "Testing 1 2 3" Use of uninitialized value $device in concatenation (.) or string at write.pl line 29. sh: -c: line 0: syntax error near unexpected token `newline' sh: -c: line 0: `echo 'foo' > ' Somehow, the regular expressions and/or the backtick escape in processing $possibledevice are not working properly, because where kwrited is connected to /dev/pts/0, the following works perfectly: $ perl write.pl "Testing 1 2 3" /dev/pts/0

    Read the article

  • Pythonic mapping of an array (Beginner)

    - by scott_karana
    Hey StackOverflow, I've got a question related to a beginner Python snippet I've written to introduce myself to the language. It's an admittedly trivial early effort, but I'm still wondering how I could have written it more elegantly. The program outputs NATO phoenetic readable versions of an argument, such "H2O" - "Hotel 2 Oscar", or (lacking an argument) just outputs the whole alphabet. I mainly use it for calling in MAC addresses and IQNs, but it's useful for other phone support too. Here's the body of the relevant portion of the program: #!/usr/bin/env python import sys nato = { "a": 'Alfa', "b": 'Bravo', "c": 'Charlie', "d": 'Delta', "e": 'Echo', "f": 'Foxtrot', "g": 'Golf', "h": 'Hotel', "i": 'India', "j": 'Juliet', "k": 'Kilo', "l": 'Lima', "m": 'Mike', "n": 'November', "o": 'Oscar', "p": 'Papa', "q": 'Quebec', "r": 'Romeo', "s": 'Sierra', "t": 'Tango', "u": 'Uniform', "v": 'Victor', "w": 'Whiskey', "x": 'Xray', "y": 'Yankee', "z": 'Zulu', } if len(sys.argv) < 2: for n in nato.keys(): print nato[n] else: # if sys.argv[1] == "-i" # TODO for char in sys.argv[1].lower(): if char in nato: print nato[char], else: print char, As I mentioned, I just want to see suggestions for a more elegant way to code this. My first guess was to use a list comprehension along the lines of [nato[x] for x in sys.argv[1].lower() if x in nato], but that doesn't allow me to output any non-alphabetic characters. My next guess was to use map, but I couldn't format any lambdas that didn't suffer from the same corner case. Any suggestions? Maybe something with first-class functions? Messing with Array's guts? This seems like it could almost be a Code Golf question, but I feel like I'm just overthinking :)

    Read the article

  • Using HAML with custom filters

    - by Guard
    Hi everybody. I feel quite excited about HAML and CoffeeScript and am working on tutorial showing how to use them in non-Rails environment. So, haml has easy to use command-line utility haml input.haml output.html. And, what is great, there exist a project (one of many forks: https://github.com/aussiegeek/coffee-haml-filter) aimed at providing custom filter that converts CoffeeScript into JS inside of HAML files. Unfortunately (or am I missing something?) haml doesn't allow specifying custom filters on the command line or with some configuration file. I (not being a Ruby fan or even knowing it enough) managed to solve it (based on some clever suggestion somewhere on SO) with this helper script: haml.rb require 'rubygems' require 'active_support/core_ext/object/blank' require 'haml' require 'haml/filters/coffee' template = ARGV.length > 0 ? File.read(ARGV.shift) : STDIN.read haml_engine = Haml::Engine.new(template) file = ARGV.length > 0 ? File.open(ARGV.shift, 'w') : STDOUT file.write(haml_engine.render) file.close Which is quite straightforward, except of requires in the beginning. Now, the questions are: 1) should I really use it, or is there another way to have on-demand HAML to HTML compilation with custom filters? 2) What about HAML watch mode? It's great and convenient. I can, of course, create a polling script in python that will watch the directory changes and call this .rb script, but it looks like a dirty solution.

    Read the article

  • python-xmpp and looping through list of recipients to receive and IM message

    - by David
    I can't figure out the problem and want some input as to whether my Python code is incorrect, or if this is an issue or design limitation of Python XMPP library. I'm new to Python by the way. Here's snippets of code in question below. What I'd like to do is read in a text file of IM recipients, one recipient per line, in XMPP/Jabber ID format. This is read into a Python list variable. I then instantiate an XMPP client session and loop through the list of recipients and send a message to each recipient. Then sleep some time and repeat test. This is for load testing the IM client of recipients as well as IM server. There is code to alternately handle case of taking only one recipient from command line input instead of from file. What ends up happening is that Python does iterate/loop through the list but only last recipient in list receives message. Switch order of recipients to verify. Kind of looks like Python XMPP library is not sending it out right, or I'm missing a step with the library calls, because the debug print statements during runtime indicate the looping works correctly. recipient = "" delay = 60 useFile = False recList = [] ... elif (sys.argv[i] == '-t'): recipient = sys.argv[i+1] useFile = False elif (sys.argv[i] == '-tf'): fil = open(sys.argv[i+1], 'r') recList = fil.readlines() fil.close() useFile = True ... # disable debug msgs cnx = xmpp.Client(svr,debug=[]) cnx.connect(server=(svr,5223)) cnx.auth(user,pwd,'imbot') cnx.sendInitPresence() while (True): if useFile: for listUser in recList: cnx.send(xmpp.Message(listUser,msg+str(msgCounter))) print "sending to "+listUser+" msg = "+msg+str(msgCounter) else: cnx.send(xmpp.Message(recipient,msg+str(msgCounter))) msgCounter += 1 time.sleep(delay)

    Read the article

  • program that writes the even and odd numbers

    - by user292489
    enter code herei was writting a program that can read a set of numbers file called dog.txt; and also writes to two file separating odd and even. i was able to compile my program however, the output expected is not the same which was supposed to be even numbers in one file called EVEN, odd numbers in file odd. #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int i; int even,odd; int num; if (argc != 4) { printf("Usage: executable in_file output_file\n"); exit(0); } FILE *dog = fopen(argv[1], "r"); FILE *feven= fopen(argv[2], "w"); FILE *fodd= fopen (argv[3], "w"); while (fscanf(dog, "%d", &num) != EOF) { if (0==i%2){ i++; printf("even= %d\n", num); } else if(i!=0){ i++; printf("odd= %d\n", num); } } fclose(feven); fclose(fodd); fclose(dog); return 0; } output: even= 1 odd= 2 even= 34 odd= 44 even= 66 odd= 78 even= 94 odd= 21 even= 23 odd= 54 even= 44 odd= 65 even= 78 odd= 68 even= 92

    Read the article

  • Listing directories in Linux from C

    - by nunos
    I am trying to simulate linux command ls using linux api from c. Looking at the code it does make sense, but when I run it I get "stat error: No such file or directory". I have checked that opendir is working ok. I think the problem is in stat, which is returning -1 even though I think it should return 0. What am I missing? Thanks for your help. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #include <sys/stat.h> #include <errno.h> int main(int argc, char *argv[]) { DIR *dirp; struct dirent *direntp; struct stat stat_buf; char *str; if (argc != 2) { fprintf( stderr, "Usage: %s dir_name\n", argv[0]); exit(1); } if ((dirp = opendir( argv[1])) == NULL) { perror(argv[1]); exit(2); } while ((direntp = readdir( dirp)) != NULL) { if (stat(direntp->d_name, &stat_buf)==-1) { perror("stat ERROR"); exit(3); } if (S_ISREG(stat_buf.st_mode)) str = "regular"; else if (S_ISDIR(stat_buf.st_mode)) str = "directory"; else str = "other"; printf("%-25s - %s\n", direntp->d_name, str); } closedir(dirp); exit(0); }

    Read the article

  • A error about "Address 0x0 is not stack'd, malloc'd or (recently) free'd" in c program under linux

    - by MaiTiano
    There is a piece of my program: height = atoi(argv[3]); width = atoi(argv[2]); sprintf(seqName,"%s", argv[1]); // strcpy(seqName, argv[1]); After compiling it, a exe file test is generated, then I use Valgrind to check it. Then I got the following message, however I cannot understand what it tends to tell me. Can anyone provide some kind help, Thanks. 1 contexts (suppressed: 13 from 8) 1 contexts (suppressed: 13 from 8) jl@ubuntu:~/work/dsr_analysis$ valgrind --tool=memcheck --leak-check=yes ./test ==28940== Memcheck, a memory error detector ==28940== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al. ==28940== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info ==28940== Command: ./test ==28940== ==28940== Invalid read of size 1 ==28940== at 0x40260CA: strcpy (mc_replace_strmem.c:311) ==28940== by 0x804A5C6: main (me_search.c:1428) ==28940== Address 0x0 is not stack'd, malloc'd or (recently) free'd ==28940== ==28940== ==28940== Process terminating with default action of signal 11 (SIGSEGV) ==28940== Access not within mapped region at address 0x0 ==28940== at 0x40260CA: strcpy (mc_replace_strmem.c:311) ==28940== by 0x804A5C6: main (me_search.c:1428) ==28940== If you believe this happened as a result of a stack ==28940== overflow in your program's main thread (unlikely but ==28940== possible), you can try to increase the size of the ==28940== main thread stack using the --main-stacksize= flag. ==28940== The main thread stack size used in this run was 8388608. ==28940== ==28940== HEAP SUMMARY: ==28940== in use at exit: 0 bytes in 0 blocks ==28940== total heap usage: 0 allocs, 0 frees, 0 bytes allocated ==28940== ==28940== All heap blocks were freed -- no leaks are possible ==28940== ==28940== For counts of detected and suppressed errors, rerun with: -v ==28940== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 13 from 8)1 contexts (suppressed: 13 from 8) 1 contexts (suppressed: 13 from 8)

    Read the article

  • How to copy an array of char pointers with a larger list of char pointers?

    - by Casey Link
    My function is being passed a struct containing, among other things, a NULL terminated array of pointers to words making up a command with arguments. I'm performing a glob match on the list of arguments, to expand them into a full list of files, then I want to replace the passed argument array with the new expanded one. The globbing is working fine, that is, g.gl_pathv is populated with the list of expected files. However, I am having trouble copying this array into the struct I was given. #include <glob.h> struct command { char **argv; // other fields... } void myFunction( struct command * cmd ) { char **p = cmd->argv; char* program = *p++; // save the program name (e.g 'ls', and increment to the first argument glob_t g; memset(&g, 0, sizeof(g)); int res = glob(*p, 0, NULL, &g); *p++ // increment while (*p) { glob(*p++, GLOB_APPEND, NULL, &g); // append the matches } // here i want to replace cmd->argv with the expanded g.gl_pathv memcpy(cmd->argv, g.gl_pathv, g.gl_pathc ); // this doesn't work globfree(&g); }

    Read the article

  • how can exec change the behavior of exec'ed program

    - by R Samuel Klatchko
    I am trying to track down a very odd crash. What is so odd about it is a workaround that someone discovered and which I cannot explain. The workaround is this small program which I'll refer to as 'runner': #include <stdio.h> #include <unistd.h> #include <string.h> #include <errno.h> int main(int argc, char *argv[]) { if (argc == 1) { fprintf(stderr, "Usage: %s prog [args ...]\n", argv[0]); return 1; } execvp(argv[1], argv + 1); fprintf(stderr, "execv failed: %s\n", strerror(errno)); // If exec returns because the program is not found or we // don't have the appropriate permission return 255; } As you can see, all this program does is use execvp to replace itself with a different program. The program crashes when it is directly invoked from the command line: /path/to/prog args # this crashes but works fine when it is indirectly invoked via my runner shim: /path/to/runner /path/to/prog args # works successfully For the life of me, I can figure out how having an extra exec can change the behavior of the program being run (as you can see the program does not change the environment). Some background on the crash. The crash itself is happening in the C++ runtime. Specifically, when the program does a throw, the crashing version incorrectly thinks there is no matching catch (although there is) and calls terminate. When I invoke the program via runner, the exception is properly caught. My question is any idea why the extra exec changes the behavior of the exec'ed program?

    Read the article

  • FILE* issue PPU side code

    - by Cristina
    We are working on a homework on CELL programming for college and their feedback response to our questions is kinda slow, thought i can get some faster answers here. I have a PPU side code which tries to open a file passed down through char* argv[], however this doesn't work it cannot make the assignment of the pointer, i get a NULL. Now my first idea was that the file isn't in the correct directory and i copied in every possible and logical place, my second idea is that maybe the PPU wants this pointer in its LS area, but i can't deduce if that's the bug or not. So... My question is what am i doing wrong? I am working with a Fedora 7 SDK Cell, with Eclipse as an IDE. Maybe my argument setup is wrong tho he gets the name of the file correctly. Code on request: images_t *read_bin_data(char *name) { FILE *file; images_t *img; uint32_t *buffer; uint8_t buf; unsigned long fileLen; unsigned long i; //Open file file = (FILE*)malloc(sizeof(FILE)); file = fopen(name, "rb"); printf("[Debug]Opening file %s\n",name); if (!file) { fprintf(stderr, "Unable to open file %s", name); return NULL; } //....... } Main launch: int main(int argc,char* argv[]) { int i,img_width; int modif_this[4] __attribute__ ((aligned(16))) = {1,2,3,4}; images_t *faces, *nonfaces; spe_context_ptr_t ctxs[SPU_THREADS]; pthread_t threads[SPU_THREADS]; thread_arg_t arg[SPU_THREADS]; //intializare img_width img_width = atoi(argv[1]); printf("[Debug]Img size is %i\n",img_width); faces = read_bin_data(argv[3]); //....... } Thanks for the help.

    Read the article

  • Segmentation fault

    - by darkie15
    #include<stdio.h> #include<zlib.h> #include<unistd.h> #include<string.h> int main(int argc, char *argv[]) { char *path=NULL; size_t size; int index ; printf("\nArgument count is = %d", argc); printf ("\nThe 0th argument to the file is %s", argv[0]); path = getcwd(path, size); printf("\nThe current working directory is = %s", path); if (argc <= 1) { printf("\nUsage: ./output filename1 filename2 ..."); } else if (argc > 1) { for (index = 1; index <= argc;index++) { printf("\n File name entered is = %s", argv[index]); strcat(path,argv[index]); printf("\n The complete path of the file name is = %s", path); } } return 0; } In the above code, here is the output that I get while running the code: $ ./output test.txt Argument count is = 2 The 0th argument to the file is ./output The current working directory is = /home/welcomeuser File name entered is = test.txt The complete path of the file name is = /home/welcomeusertest.txt Segmentation fault (core dumped) Can anyone please me understand why I am getting a core dumped error? Regards, darkie

    Read the article

  • Can someone explain me this code ?

    - by VaioIsBorn
    #include <stdio.h> #include <unistd.h> #include <string.h> int good(int addr) { printf("Address of hmm: %p\n", addr); } int hmm() { printf("Win.\n"); execl("/bin/sh", "sh", NULL); } extern char **environ; int main(int argc, char **argv) { int i, limit; for(i = 0; environ[i] != NULL; i++) memset(environ[i], 0x00, strlen(environ[i])); int (*fptr)(int) = good; char buf[32]; if(strlen(argv[1]) <= 40) limit = strlen(argv[1]); for(i = 0; i <= limit; i++) { buf[i] = argv[1][i]; if(i < 36) buf[i] = 0x41; } int (*hmmptr)(int) = hmm; (*fptr)((int)hmmptr); return 0; } I don't really understand the code above, i have it from an online game - i should supply something in the arguments so it would give me shell, but i don't get it how it works so i don't know what to do. So i need someone that would explain it what it does, how it's working and the stuff. Thanks.

    Read the article

  • Error when linking C executable to OpenCV

    - by Ghilas BELHADJ
    I'm compiling OpenCV under Ubuntu 13.10 using cMake. i've already compiled c++ programs and they works well. now i'm trying to compile a C file using this cMakeLists.txt cmake_minimum_required (VERSION 2.8) project (hello) find_package (OpenCV REQUIRED) add_executable (hello src/test.c) target_link_libraries (hello ${OpenCV_LIBS}) here is the test.c file: #include <stdio.h> #include <stdlib.h> #include <opencv/highgui.h> int main (int argc, char* argv[]) { IplImage* img = NULL; const char* window_title = "Hello, OpenCV!"; if (argc < 2) { fprintf (stderr, "usage: %s IMAGE\n", argv[0]); return EXIT_FAILURE; } img = cvLoadImage(argv[1], CV_LOAD_IMAGE_UNCHANGED); if (img == NULL) { fprintf (stderr, "couldn't open image file: %s\n", argv[1]); return EXIT_FAILURE; } cvNamedWindow (window_title, CV_WINDOW_AUTOSIZE); cvShowImage (window_title, img); cvWaitKey(0); cvDestroyAllWindows(); cvReleaseImage(&img); return EXIT_SUCCESS; } it returns me this error whene running cmake . then make to the project: Linking C executable hello /usr/bin/ld: CMakeFiles/hello.dir/src/test.c.o: undefined reference to symbol «lrint@@GLIBC_2.1» /lib/i386-linux-gnu/libm.so.6: error adding symbols: DSO missing from command line collect2: error: ld returned 1 exit status make[2]: *** [hello] Erreur 1 make[1]: *** [CMakeFiles/hello.dir/all] Erreur 2 make: *** [all] Erreur 2

    Read the article

  • leak in fgets when assigning to buffer

    - by monkeyking
    I'm having problems understanding why following code leaks in one case, and not in the other case. The difference is while(NULL!=fgets(buffer,length,file))//doesnt leak while(NULL!=(buffer=fgets(buffer,length,file))//leaks I thought it would be the same. Full code below. #include <stdio.h> #include <stdlib.h> #define LENS 10000 void no_leak(const char* argv){ char *buffer = (char *) malloc(LENS); FILE *fp=fopen(argv,"r"); while(NULL!=fgets(buffer,LENS,fp)){ fprintf(stderr,"%s",buffer); } fclose(fp); fprintf(stderr,"%s\n",buffer); free(buffer); } void with_leak(const char* argv){ char *buffer = (char *) malloc(LENS); FILE *fp=fopen(argv,"r"); while(NULL!=(buffer=fgets(buffer,LENS,fp))){ fprintf(stderr,"%s",buffer); } fclose(fp); fprintf(stderr,"%s\n",buffer); free(buffer); }

    Read the article

  • git-diff to ignore ^M

    - by neoneye
    In a project where some of the files contains ^M as newline separators. Diffing these files are apparently impossible, since git-diff sees it as the entire file is just a single line. How does one diff with the previous version? Is there an option like "treat ^M as newline when diffing" ? prompt> git-diff "HEAD^" -- MyFile.as diff --git a/myproject/MyFile.as b/myproject/MyFile.as index be78321..a393ba3 100644 --- a/myproject/MyFile.cpp +++ b/myproject/MyFile.cpp @@ -1 +1 @@ -<U+FEFF>import flash.events.MouseEvent;^Mimport mx.controls.*;^Mimport mx.utils.Delegate \ No newline at end of file +<U+FEFF>import flash.events.MouseEvent;^Mimport mx.controls.*;^Mimport mx.utils.Delegate \ No newline at end of file prompt> UPDATE: now I have written a script that checks out the latest 10 revisions and converts CR to LF. require 'fileutils' if ARGV.size != 3 puts "a git-path must be provided" puts "a filename must be provided" puts "a result-dir must be provided" puts "example:" puts "ruby gitcrdiff.rb project/dir1/dir2/dir3/ SomeFile.cpp tmp_somefile" exit(1) end gitpath = ARGV[0] filename = ARGV[1] resultdir = ARGV[2] unless FileTest.exist?(".git") puts "this command must be run in the same dir as where .git resides" exit(1) end if FileTest.exist?(resultdir) puts "the result dir must not exist" exit(1) end FileUtils.mkdir(resultdir) 10.times do |i| revision = "^" * i cmd = "git show HEAD#{revision}:#{gitpath}#{filename} | tr '\\r' '\\n' > #{resultdir}/#{filename}_rev#{i}" puts cmd system cmd end

    Read the article

  • C: socket connection timeout

    - by The.Anti.9
    I have a simple program to check if a port is open, but I want to shorten the timeout length on the socket connection because the default is far too long. I'm not sure how to do this though. Here's the code: #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <arpa/inet.h> #include <netinet/in.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <netdb.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc, char **argv) { u_short port; /* user specified port number */ char addr[1023]; /* will be a copy of the address entered by u */ struct sockaddr_in address; /* the libc network address data structure */ short int sock = -1; /* file descriptor for the network socket */ if (argc != 3) { fprintf(stderr, "Usage %s <port_num> <address>", argv[0]); return EXIT_FAILURE; } address.sin_addr.s_addr = inet_addr(argv[2]); /* assign the address */ address.sin_port = htons(atoi(argv[2])); /* translate int2port num */ sock = socket(AF_INET, SOCK_STREAM, 0); if (connect(sock,(struct sockaddr *)&address,sizeof(address)) == 0) { printf("%i is open\n", port); } close(sock); return 0; }

    Read the article

  • Simple binary File I/O problem with cstdio(c++)

    - by Atilla Filiz
    The c++ program below fails to read the file. I know using cstdio is not good practice but that what I am used to and it should work anyway. $ ls -l l.uyvy -rw-r--r-- 1 atilla atilla 614400 2010-04-24 18:11 l.uyvy $ ./a.out l.uyvy Read 0 bytes out of 614400, possibly wrong file code: #include<cstdio> int main(int argc, char* argv[]) { FILE *fp; if(argc<2) { printf("usage: %s <input>\n",argv[0]); return 1; } fp=fopen(argv[1],"rb"); if(!fp) { printf("erör, cannot open %s for reading\n",argv[1]); return -1; } int bytes_read=fread(imgdata,1,2*IMAGE_SIZE,fp); //2bytes per pixel fclose(fp); if(bytes_read < 2*IMAGE_SIZE) { printf("Read %d bytes out of %d, possibly wrong file\n", bytes_read, 2*IMAGE_SIZE); return -1; } return 0; }

    Read the article

  • How do I cover unintuitive code blocks?

    - by naivedeveloper
    For some reason, I'm having a hard time trying to cover the block of code below. This code is an excerpt from the UNIX uniq command. I'm trying to write test cases to cover all blocks, but can't seem to reach this block: if (nfiles == 2) { // Generic error routine } In context: int main (int argc, char **argv) { int optc = 0; bool posixly_correct = (getenv ("POSIXLY_CORRECT") != NULL); int nfiles = 0; char const *file[2]; file[0] = file[1] = "-"; program_name = argv[0]; skip_chars = 0; skip_fields = 0; check_chars = SIZE_MAX; for (;;) { /* Parse an operand with leading "+" as a file after "--" was seen; or if pedantic and a file was seen; or if not obsolete. */ if (optc == -1 || (posixly_correct && nfiles != 0) || ((optc = getopt_long (argc, argv, "-0123456789Dcdf:is:uw:", longopts, NULL)) == -1)) { if (optind == argc) break; if (nfiles == 2) { // Handle errors } file[nfiles++] = argv[optind++]; } else switch (optc) { case 1: { unsigned long int size; if (optarg[0] == '+' && posix2_version () < 200112 && xstrtoul (optarg, NULL, 10, &size, "") == LONGINT_OK && size <= SIZE_MAX) skip_chars = size; else if (nfiles == 2) { // Handle error } else file[nfiles++] = optarg; } break; } } } Any help would be greatly appreciated. Thanks.

    Read the article

  • Pass arguments to a parameter class object

    - by David R
    This is undoubtedly a simple question. I used to do this before, but it's been around 10 years since I worked in C++ so I can't remember properly and I can't get a simple constructor call working. The idea is that instead of parsing the args in main, main would create an object specifically designed to parse the arguments and return them as required. So: Parameters params = new Parameters(argc, argv) then I can call things like params.getfile() Only problem is I'm getting a complier error in Visual Studio 2008 and I'm sure this is simple, but I think my mind is just too rusty. What I've got so far is really basic: In the main: #include "stdafx.h" #include "Parameters.h" int _tmain(int argc, _TCHAR* argv[]) { Parameters params = new Parameters(argc, argv); return 0; } Then in the Parameters header: #pragma once class Parameters { public: Parameters(int, _TCHAR*[]); ~Parameters(void); }; Finally in the Parameters class: include "Stdafx.h" #include "Parameters.h" Parameters::Parameters(int argc, _TCHAR* argv[]) { } Parameters::~Parameters(void) { } I would appreciate if anyone could see where my ageing mind has missed the really obvious. Thanks in advance.

    Read the article

  • Simulation tree command in C

    - by Ecle
    I have to create the simulation of tree command in C, this is my current code: #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <string.h> main(int argc, char *argv[]){ int i; if(argc < 2){ printf("\nError. Use: %s directory\n", argv[0]); system("exit"); } for(i=1;i<argc;i++) //if(argv[i][0] != '-') tree(argv[i]); } tree(char *ruta){ DIR *dirp; struct dirent *dp; static nivel = 0; struct stat buf; char fichero[256]; int i; if((dirp = opendir(path)) == NULL){ perror(path); return; } while((dp = readdir(dirp)) != NULL){ printf(fichero, "%s/%s", path, dp->d_name); if((buf.st_mode & S_IFMT) == S_IFDIR){ for(i=0;i<nivel;i++) printf("\t"); printf("%s\n", dp->d_name); ++nivel; tree(fichero); --nivel; } } } Apparently, it works! (due to it compiles correctly) But I don't why. I can't pass the correct arguments to execute this. Thank you so much, people.

    Read the article

  • What is the difference between _tmain() and main() in C++?

    - by joshcomley
    If I run my C++ application with the following main() method everything is OK: int main(int argc, char *argv[]) { cout << "There are " << argc << " arguments:" << endl; // Loop through each argument and print its number and value for (int i=0; i<argc; i++) cout << i << " " << argv[i] << endl; return 0; } I get what I expect and my arguments are printed out. However, if I use _tmain: int _tmain(int argc, char *argv[]) { cout << "There are " << argc << " arguments:" << endl; // Loop through each argument and print its number and value for (int i=0; i<argc; i++) cout << i << " " << argv[i] << endl; return 0; } It just displays the first character of each argument. What is the difference causing this?

    Read the article

  • A/UX cc compiler errors on trivial code: "declared argument argc is missing"

    - by Fzn
    On a quite ancient UNIX (Apple A/UX 3.0.1 for 680x0 processors) using the built-in c compiler (cc), this issue arrises. Here is the code I'm trying to compile: #include <stdlib.h> #include <stdio.h> int main() int argc; char **argv; { if (argc > 1) puts(argv[1]); return (EXIT_SUCCESS); } And here is the output I get: pigeonz.root # cc -c test.c "test.c", line 5: declared argument argc is missing "test.c", line 6: declared argument argv is missing Using a more modern prototype did not help, nor did the manual page, nor a quick google search. What am I doing wrong?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >