Search Results

Search found 172 results on 7 pages for 'fgets'.

Page 1/7 | 1 2 3 4 5 6 7  | Next Page >

  • fgets, sscanf, and writing to arrays

    - by alldavidsluck
    beginner question here, I haven't been able to find examples that relate. I'm working on a C program that will take integer input from stdin using fgets and sscanf, and then write it to an array. However, I'm not sure how to make fgets write to the array. #define MAXINT 512 char input[MAXINT] int main(void) { int i; int j; int count=0; int retval; while (1==1) { fgets(input, MAXINT[count], stdin); retval = sscanf(input, "%d", &i); if (retval == 1) { count = count++; } else if (retval != 1) { break; } } Would I simply put fgets in a for loop? or is it more complicated than that?

    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

  • question about fgets

    - by user105033
    Is this safe to do? (does fgets terminate the buffer with null) or should I be setting the 20th byte to null after the call to fgets before i call clean. // strip new lines void clean(char *data) { while (*data) { if (*data == '\n' || *data == '\r') *data = '\0'; data++; } } // for this, assume that the file contains 1 line no longer than 19 bytes // buffer is freed elsewhere char *load_latest_info(char *file) { FILE *f; char *buffer = (char*) malloc(20); if (f = fopen(file, "r")) if (fgets(buffer, 20, f)) { clean(buffer); return buffer; } free(buffer); return NULL; }

    Read the article

  • Are fopen/fread/fgets PID-safe in C ?

    - by Jane
    Various users are browsing through a website 100% programmed in C (CGI). Each webpage uses fopen/fgets/fread to read common data (like navigation bars) from files. Would each call to fopen/fgets/fread interefere with each other if various people are browsing the same page ? If so, how can this be solved in C ? (This is a Linux server, compiling is done with gcc and this is for a CGI website programmed in C.) Example: FILE *DATAFILE = fopen(PATH, "r"); if ( DATAFILE != NULL ) { while ( fgets( LINE, BUFFER, DATAFILE ) ) { /* do something */ } }

    Read the article

  • ignore extra spaces when using fgets

    - by Gary
    Hi, I'm using fgets with stdin to read in some data, with the max length i read in being 25. With one of the tests I'm running on this code, there are a few hundred spaces after the data that I want - which causes the program to fail. Can someone advise me as to how to ignore all of these extra spaces when using fgets and go to the next line? Thanks

    Read the article

  • fgets instructions gets skipped.Why?

    - by nunos
    Whenever I do a scanf before a fgets the fgets instruction gets skipped. I have come accross this issue in C++ and I remember I had to had some instrcution that would clear the stdin buffer or something like that. I suppose there's an equivalent for C. What is it? Thanks.

    Read the article

  • check whether fgets would block

    - by lv
    Hi, I was just wondering whether in C is it possible to peek in the input buffer or perform similar trickery to know whether a call to fgets would block at a later time. Java allows to do something like that by calling BufferedReader.ready(), this way I can implement console input something like this: while (on && in.ready()) { line = in.readLine(); /* do something with line */ if (!in.ready()) Thread.sleep(100); } this allows an external thread to gracefully shutdown the input loop by setting on to false; I'd like to perform a similar implementation in C without resorting to non portable tricks, I already know I can make a "timed out fgets" under unix by resorting to signals or (better, even though requering to take care of buffering) reimplement it on top of recv/select, but I'd prefer something that would work on windows too. TIA

    Read the article

  • fgets equilvilant in C++

    - by mitchell
    what is the C++ equivilant to the c function fgets? I have looked at getline from ifstream, but when it comes to a end of line character, '\n', it terminates at and discards it, I am looking for a function that just terminates at the end line character but adds the end of line character to the char array. thanks in advance

    Read the article

  • fgets and strcmp [C]

    - by Blackbinary
    I'm trying to compare two strings. One stored in a file, the other retrieved from the user (stdin). Here is a sample program: int main() { char targetName[50]; fgets(targetName,50,stdin); char aName[] = "bob"; printf("%d",strcmp(aName,targetName)); return 0; } In this program, strcmp returns a value of -1 when the input is 'bob'. Why is this? I thought they should be equal. How can i get it so that they are?

    Read the article

  • Removing trailing newline character from fgets() input

    - by sfactor
    i am trying to get some data from the user and send it to another function in gcc. the code is something like this. printf("Enter your Name: "); if(!(fgets(Name, sizeof Name, stdin) != NULL)) { fprintf(stderr, "Error reading Name.\n"); exit(1); } However, i find that it has an \n character in the end. so if i enter John it ends up sending John\n. so how do i remove that \n and send a proper string.

    Read the article

  • In Perl, can I limit the length of a line as I read it in from a file (like fgets)

    - by SB
    I'm trying to write a piece of code that reads a file line by line and stores each line, up to a certain amount of input data. I want to guard against the end-user being evil and putting something like a gig of data on one line in addition to guarding against sucking in an abnormally large file. Doing $str = <FILE> will still read in a whole line, and that could be very long and blow up my memory. fgets lets me do this by letting me specify a number of bytes to read during each call and essentially letting me split one long line into my max length. Is there a similar way to do this in perl? I saw something about sv_gets but am not sure how to use it (though I only did a cursory Google search). Thanks.

    Read the article

  • Using fgets to read strings from file in C

    - by Ivan
    I am trying to read strings from a file that has each string on a new line but I think it reads a newline character once instead of a string and I don't know why. If I'm going about reading strings the wrong way please correct me. i=0; F1 = fopen("alg.txt", "r"); F2 = fopen("tul.txt", "w"); if(!feof(F1)) { do{ //start scanning file fgets(inimene[i].Enimi, 20, F1); fgets(inimene[i].Pnimi, 20, F1); fgets(inimene[i].Kood, 12, F1); printf("i=%d\nEnimi=%s\nPnimi=%s\nKaad=%s",i,inimene[i].Enimi,inimene[i].Pnimi,inimene[i].Kood); i++;} while(!feof(F1));}; /*finish getting structs*/ The printf is there to let me see what was read into what and here is the result i=0 Enimi=peter Pnimi=pupkin Kood=223456iatb i=1 Enimi= Pnimi=masha Kaad=gubkina i=2 Enimi=234567iasb Pnimi=sasha Kood=dudkina As you can see after the first struct is read there is a blank(a newline?) onct and then everything is shifted. I suppose I could read a dummy string to absorb that extra blank and then nothing would be shifted, but that doesn't help me understand the problem and avoid in the future.

    Read the article

  • fgets throwing unhandled exception while parsing stl

    - by user3478400
    I am new to c++, I am trying to parse a stl file which is of about 64MB and has about ~18K lines in it. The code works fine for first few 100 lines but then fgets throws following exception: "Unhandled exception at 0x77B0BAC5 (ntdll.dll) in STLparser.exe: 0xC0000024: There is a mismatch between the type of object required by the requested operation and the type of object that is specified in the request." I have checked manually the line for which fgets throws exception, there is nothing out of ordinary there. I am out of options for now. Any help to fix this issue will be greatly appreciated. ================CODE========================== #include<fstream> #include<iostream> #include"ParseString.h" #include"Vectors.h" using namespace std; int main(void) { //Define variables FILE *file; char *line = new char; parsestring oneline; int n_Vols = 0, n_Elms = 0, n_nods = -1, E = 0; Nod *nodes = new Nod(); Nod dummy; Elm *elements = new Elm(); int mycounter = 0; //Open file fopen_s(&file, "sample.stl", "r"); while (fgets(line, 1024, file) != NULL) //**********Getting Error Here************* { // populate required data } fclose(file); printf("%d,%d,%d", n_Vols, n_Elms, n_nods); getchar(); return 0; } ===================When broken, execution resumes at this function (not my function, something internal) void __cdecl _unlock ( int locknum ) { /* * leave the critical section. */ LeaveCriticalSection( _locktable[locknum].lock ); }

    Read the article

  • how does fgets internally works?

    - by Registered User
    Well it is a basic question but I seem confused enough. #include<stdio.h> int main() { char a[100]; printf("Enter a string\n"); scanf("%s",a); } Basically the above is what I want to achieve. If I enter a string James Bond then I want that to be stored in array a. But the problem is because of presence of a blank space in between only James word is stored. So how can I solve this one. UPDATE After the replies given below I understand fgets() would be a better choice. I want to know internal working of fgets as why is it able to store the string with space where as scanf is not able to do the same.

    Read the article

  • fgets in c doesn't return a portion of an string

    - by Marc
    Hi! I'm totally new in C, and I'm trying to do a little application that searches a string into a file, my problem is that I need to open a big file (more than 1GB) with just one line inside and fgets return me the entire file (I'm doing test with a 10KB file). actually this is my code: #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char *search = argv[argc-1]; int retro = strlen(search); int pun = 0; int sortida; int limit = 10; char ara[20]; FILE *fp; if ((fp = fopen ("SEARCHFILE", "r")) == NULL){ sortida = -1; exit (1); } while(!feof(fp)){ if (fgets(ara, 20, fp) == NULL){ break; } //this must be a 20 bytes line, but it gets the entyre 10Kb file printf("%s",ara); } sortida = 1; if(fclose(fp) != 0){ sortida = -2; exit (1); } return 0; } What can I do to find an string into a file? I'v tried with GREP but it don't helps, because it returns the position:ENTIRE_STRING. I'm open to ideas. Thanks in advance!

    Read the article

  • fgets in c don't return a portion of an string

    - by Marc
    Hi! I'm totally new in C, and I'm trying to do a little application that searches a string into a file, my problem is that I need to open a big file (more than 1GB) with just one line inside and fgets return me the entire file (I'm doing test with a 10KB file). actually this is my code: #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char *search = argv[argc-1]; int retro = strlen(search); int pun = 0; int sortida; int limit = 10; char ara[20]; FILE *fp; if ((fp = fopen ("SEARCHFILE", "r")) == NULL){ sortida = -1; exit (1); } while(!feof(fp)){ if (fgets(ara, 20, fp) == NULL){ break; } //this must be a 20 bytes line, but it gets the entyre 10Kb file printf("%s",ara); } sortida = 1; if(fclose(fp) != 0){ sortida = -2; exit (1); } return 0; } What can I do to find an string into a file? I'v tried with GREP but it don't helps, because it returns the position:ENTIRE_STRING. I'm open to ideas. Thanks in advance!

    Read the article

  • Using PHP to read a web page with fsockopen(), but fgets is not working

    - by asdasd
    Im using this code here: http://www.digiways.com/articles/php/httpredirects/ public function ReadHttpFile($strUrl, $iHttpRedirectMaxRecursiveCalls = 5) { // parsing the url getting web server name/IP, path and port. $url = parse_url($strUrl); // setting path to '/' if not present in $strUrl if (isset($url['path']) === false) $url['path'] = '/'; // setting port to default HTTP server port 80 if (isset($url['port']) === false) $url['port'] = 80; // connecting to the server] // reseting class data $this->success = false; unset($this->strFile); unset($this->aHeaderLines); $this->strLocation = $strUrl; $fp = fsockopen ($url['host'], $url['port'], $errno, $errstr, 30); // Return if the socket was not open $this-success is set to false. if (!$fp) return; $header = 'GET / HTTP/1.1\r\n'; $header .= 'Host: '.$url['host'].$url['path']; if (isset($url['query'])) $header .= '?'.$url['query']; $header .= '\r\n'; $header .= 'Connection: Close\r\n\r\n'; // sending the request to the server echo "Header is: ".str_replace('\n', '\n', $header).""; $length = strlen($header); if($length != fwrite($fp, $header, $length)) { echo 'error writing to header, exiting'; return; } // $bHeader is set to true while we receive the HTTP header // and after the empty line (end of HTTP header) it's set to false. $bHeader = true; // continuing untill there's no more text to read from the socket while (!feof($fp)) { echo "in loop"; // reading a line of text from the socket // not more than 8192 symbols. $good = $strLine = fgets($fp, 128); if(!$good) { echo 'bad'; return; } // removing trailing \n and \r characters. $strLine = ereg_replace('[\r\n]', '', $strLine); if ($bHeader == false) $this-strFile .= $strLine.'\n'; else $this-aHeaderLines[] = trim($strLine); if (strlen($strLine) == 0) $bHeader = false; echo "read: $strLine"; return; } echo "after loop"; fclose ($fp); } This is all I get: Header is: GET / HTTP/1.1\r\n Host: www.google.com/\r\n Connection: Close\r\n\r\n in loopbad So it fails the fgets($fp, 128);

    Read the article

  • C child read giving "resource temporarily unavailable"

    - by Gary
    So I have a file stream from a parent process to a child - and most of the time it works fine. However, when reading from it multiple times quickly, using fgets() will return NULL and the error is set to "resource temporarily unavailable". The problem is intermittent - and running the script that does the reads will sometimes have fgets return NULL and sometimes wont. Could anyone help me stop this error from happening? Thanks!

    Read the article

  • PHP fastest method of reading server response

    - by Peter John
    Hi there, im having some real problems with the lag produced by using fgets to grab the server's response to some batch database calls im making. Im sending through a batch of say, 10,000 calls and ive tracked the lag down to fgets causing the hold up in the speed of my application as the response for each call needs to be grabbed. I have found this thread http://bugs.php.net/bug.php?id=32806 which explains the problem quite well, but hes reading a file, not a server response so fread could be a bit tricky as i could get part of the next line, and extra stuff which i dont want. Any help much appreciated!

    Read the article

  • fsockopen soap request

    - by gosom
    I am trying to send a SOAP message to a service using php. I want to do it with fsockopen, here's is the code : <?php $fp = @fsockopen("ssl://xmlpropp.worldspan.com", 443, $errno, $errstr); if (!is_resource($fp)) { die('fsockopen call failed with error number ' . $errno . '.' . $errstr); } $soap_out = "POST /xmlts HTTP/1.1\r\n"; $soap_out .= "Host: 212.127.18.11:8800\r\n"; //$soap_out .= "User-Agent: MySOAPisOKGuys \r\n"; $soap_out .= "Content-Type: text/xml; charset='utf-8'\r\n"; $soap_out .= "Content-Length: 999\r\n\r\n"; $soap_put .= "Connection: close\r\n"; $soap_out .= "SOAPAction:\r\n"; $soap_out .= ' Worldspan This is a test '; if(!fputs($fp, $soap_out, strlen($soap_out))) echo "could not write"; echo "<xmp>".$soap_out."</xmp>"; echo "--------------------<br>"; while (!feof($fp)) { $soap_in .= fgets($fp, 100); } echo "<xmp>$soap_in</xmp>"; fclose($fp); echo "ok"; the above code just hangs . if i remove the while it types ok, so i suppose the problem is at $soap_in .= fgets($fp, 100) Any ideas of what is happening

    Read the article

  • Editing a remote file on-the-fly with PHP

    - by user275074
    Hi, I have a requirement to edit a remote text file on-the-fly, the content of which currently stands at ~1Mb. I have tried a couple of approaches and both seem to be clunky or hog memory which I can't rely on. Thinking out logically what I'm trying to achieve is: FTP to a remote server. Download a copy of the file for backup purposes and store it somewhere locally. Open the remote file and add the necessary lines required. Remove lines from the remote file as per an array of un-required data generated from the local server. Is this possible? I've managed to code steps 1 and 2 but I'm having difficult with 3 and 4. The way I'm doing it now is to use fgets and return the whole string. Really, I don't want to do this as it involves manipulating and re-generating the whole string (and it's large) and then re-inserting it in between two markers in the remote file. Is there no way of manipulating the lines of text in the file on-the-fly?

    Read the article

  • Howto open a file and remove the last line?

    - by sologhost
    I am looking to open up a file, grab the last line in the file where the line = "?", which is the closing tag for a php document. Than I am wanting to append data into it and add back in the "?" to the very last line. I've been trying a few approaches, but I'm not having any luck. Here's what I got so far, as I am reading from a zip file. Though I know this is all wrong, just needing some help with this please... // Open for reading is all we can do with zips and is all we need. if (zip_entry_open($zipOpen, $zipFile, "r")) { $fstream = zip_entry_read($zipFile, zip_entry_filesize($zipFile)); $fp = fopen($curr_lang_file, 'r+b'); while (!feof($fp)) { $output = fgets($fp, 16384); if (trim($output) == '?>') break; fwrite($fp, $output); } fclose($fp); file_put_contents($curr_lang_file, $fstream, FILE_APPEND); } $curr_lang_file is a filepath string to the actual file that needs to have the fstream appended to it, but after we remove the last line that equals '?'

    Read the article

  • How to open a file and remove the last line?

    - by sologhost
    I am looking to open up a file, grab the last line in the file where the line = "?", which is the closing tag for a php document. Than I am wanting to append data into it and add back in the "?" to the very last line. I've been trying a few approaches, but I'm not having any luck. Here's what I got so far, as I am reading from a zip file. Though I know this is all wrong, just needing some help with this please... // Open for reading is all we can do with zips and is all we need. if (zip_entry_open($zipOpen, $zipFile, "r")) { $fstream = zip_entry_read($zipFile, zip_entry_filesize($zipFile)); $fp = fopen($curr_lang_file, 'r+b'); while (!feof($fp)) { $output = fgets($fp, 16384); if (trim($output) == '?>') break; fwrite($fp, $output); } fclose($fp); file_put_contents($curr_lang_file, $fstream, FILE_APPEND); } $curr_lang_file is a filepath string to the actual file that needs to have the fstream appended to it, but after we remove the last line that equals '?'

    Read the article

1 2 3 4 5 6 7  | Next Page >