Writing String to File in C - html

I am in the process of writing an HTTP client that basically goes to a webpage and downloads the content to a separate file, which the user defines. I am having trouble not with the act of writing to a file itself, but I'm getting a strange problem. I'll show a couple of the code snippets below, but basically when there is a
fprintf(stdout, "%s", htmlcontent);
where htmlcontent is defined as
char *htmlcontent;
it prints out the entire HTML page information to the standard output. I can also redirect this output to a file in the command line by saying >myfile.txt (Yes, I want to compare the text files instead of html files).
But when I do something like this:
fprintf(savedfile, "%s", htmlcontent);
where savedfile is defined as
FILE *savedfile;
and it is opened like this:
savedfile = fopen(filename, "w");
where filename is defined as
char *filename;
and is set equal to the command line argument that corresponds to it. When I do the second type of fprintf to print it out to my file instead of the standard output, I do not get the same thing and i can't figure out why. Can anybody help me understand why there would be any difference? If you want me to post the two different programs so you can see them in their entirety just let me know and I'll do that.

You haven't really told us what the difference is between the two output methods but, based on the information given, there should be none.
Functionally, there's no difference between writing to stdout and any other properly opened output stream (there are some behavioural differences like buffering but they shouldn't affect the output).
The following transcript shows this in action:
pax> cat xyzzy.c
#include <stdio.h>
int main (void) {
char *filename = "xyzzy.txt";
char *html = "<tag>some markup</tag>\n";
FILE *xyzzy = fopen (filename, "w"); // should error check
fprintf (stdout, "%s", html);
fprintf (xyzzy, "%s", html);
fclose (xyzzy);
return 0;
}
pax> ./xyzzy
<tag>some markup</tag>
pax> cat xyzzy.txt
<tag>some markup</tag>
As you can see, both the xyzzy.txt file and the standard output of the program contain the same information.

Related

Windows (command line) tool to convert non-ascii characters to HTML numeric codes [duplicate]

I need to replicate the exact function this website http://www.unicodetools.com/unicode/convert-to-html.php does in a hybrid Javascript/Windows batch script. I have zero knowledge about Javascript but it seems it is the easiest (for those knowledgeable) possible way to replace special non-ASCII characters with their HTML entity equivalents within text files: "têxt" to "têxt", for example, but using input and output text files instead of web forms. I've seen the wonders JREPL.bat (a regex/find and replace tool) does so I thought this could be achieved.
Pardon me for asking this question but this is part of a problem I could not wrap my head around for days. It is in regard to this unanswered question, https://stackoverflow.com/questions/35121949/curl-data-urlencode-posts-broken-non-english-characters. I figured out that the Japanese and other UTF-8 characters in the text file can be passed through CURL post request without being garbled by first encoding them to HTML code before the --data-urlencode part.
That said, I am kindly asking if someone would be so kind as to create a simple JScript/Windows batch script hybrid incorporating the Javascript code the above-mentioned website uses to encode only non-ASCII characters to HTML entities within a text file which I can call from another batch file using a line of code like this:
CALL EncodetoHTML.bat -i "input.txt" -o "output.txt"
Here it is . Brand new and fresh.
You can pass only the file you want to encode (the result will be printed to the console) or pass input and output file.Examples:
call toHtmlEnt.bat input.txt output.txt
call toHtmlEnt.bat input.txt
I wrote my own script. It took me a whole day basically scouring the Internet for useful pieces of code I could find and combining them to achieve the effect I wanted.
Save the code below to tohtmlent.bat. Use it from CMD like tohtmlent.bat filename.txt or call it from another batch file like call tohtmlent.bat filename.txt where "filename.txt" is the input file. Output will be displayed in the console so use > if you would like to pipe the output to a file. The input file should strictly be encoded in UTF-8. Output is ANSI. What the script does is it converts all Unicode characters with decimal range 128 and higher to their numeric HTML entity equivalents.
The code is nowhere near elegant considering I am not a programmer and it still has a lot more room for improvement. But hey, it does its job!
#if (#X)==(#Y) #end /*
#echo off
cscript //E:JScript //nologo "%~f0" %*
exit /b 0
*/
if (WScript.Arguments.Length < 1 ) {
WScript.Echo("No file specified.");
WScript.Quit(0)
}
var inputFile = WScript.Arguments.Item(0);
var fso= new ActiveXObject("Scripting.FileSystemObject");
var inputFile=WScript.Arguments.Item(0);
if (!fso.FileExists(inputFile)){
WScript.Echo(inputFile + " does not exist.");
WScript.Quit(1);
}
var objAdoS = WScript.CreateObject("ADODB.Stream");
objAdoS.Type = 2;
objAdoS.CharSet = "utf-8";
objAdoS.Open();
objAdoS.LoadFromFile(inputFile);
var strInput = objAdoS.ReadText();
objAdoS.Close();
var strOutput = '';
for(i=0; i<strInput.length; i++){
if(strInput.charCodeAt(i)>127){ strOutput += '&#' + strInput.charCodeAt(i) + ';'; }else{ strOutput += strInput.charAt(i); }
}
WScript.Echo(strOutput);

It is possible to obtain the mean of different files to make some computations with it after?

I have a code to calculate the mean of the first five values of each column of a file, for then use these values as a reference point for all set. The problem is that now I need to do the same but for many files. So I will need to obtain the mean of each file to then use these values again with the originals files. I have tried in this way but I obtain an error. Thanks.
%%% - Loading the file of each experiment
myfiles = dir('*.lvm'); % To load every file of .lvm
for i = 1:length(myfiles) % Loop with the number of files
files=myfiles(i).name;
mydata(i).files = files;
mydata(i).T = fileread(files);
arraymean(i) = mean(mydata(i));
end
The files that I need to compute are more or less like this:
Delta_X 3.000000 3.000000 3.000000
***End_of_Header***
X_Value C_P1N1 C_P1N2 C_P1N3
0.000000 -0.044945 -0.045145 -0.045705
0.000000 -0.044939 -0.045135 -0.045711
3.000000 -0.044939 -0.045132 -0.045706
6.000000 -0.044938 -0.045135 -0.045702
Your first line results in 'myfiles' being a structure array with components that you will find defined when you type 'help dir'. In particular, the names of all the files are contained in the structure element myfiles(i).name. To display all the file names, type myfiles.name. So far so good. In the for loop you use 'fileread', but fileread (see help fileread) returns the character string rather than the actual values. I have named your prototype .lvm file DinaF.lvm and I have written a very, very simple function to read the data in that file, by skipping the first three lines, then storing the following matrix, assumed to have 4 columns, in an array called T inside the function and arrayT in the main program
Here is a modified script, where a function read_lvm has been included to read your 'model' lvm file.
The '1' in the first line tells Octave that there is more to the script than just the following function: the main program has to be interpreted as well.
1;
function T=read_lvm(filename)
fid = fopen (filename, "r");
%% Skip by first three lines
for lhead=1:3
junk=fgetl(fid);
endfor
%% Read nrow lines of data, quit when file is empty
nrow=0;
while (! feof (fid) )
nrow=nrow + 1;
thisline=fscanf(fid,'%f',4);
T(nrow,1:4)=transpose(thisline);
endwhile
fclose (fid);
endfunction
## main program
myfiles = dir('*.lvm'); % To load every file of .lvm
for i = 1:length(myfiles) % Loop with the number of files
files=myfiles(i).name;
arrayT(i,:,:) = read_lvm(files);
columnmean(i,1:4)=mean(arrayT(i,:,:))
end
Now the tabular values associated with each .lvm file are in the array arrayT and the mean for that data set is in columnmean(i,1:4). If i>1 then columnmean would be an array, with each row containing the files for each lvm file. T
This discussion is getting to be too distant from the initial question. I am happy to continue to help. If you want more help, close this discussion by accepting my answer (click the swish), then ask a new question with a heading like 'How to read .lvm files in Octave'. That way you will get the insights from many more people.

using a variable to identify file in 'print -dpdf file_name'

I am trying to use a formatted string to identify the file location when using 'print -dpdf file_name' to write a plot (or figure) to a file.
I've tried:
k=1;
file_name = sprintf("\'/home/user/directory to use/file%3.3i.pdf\'",k);
print -dpdf file_name;
but that only gets me a figure written to ~/file_name.pdf which is not what I want. I've tried several other approaches but I cannot find an approach that causes the the third term (file_name, in this example) to be evaluated. I have not found any other printing function that will allow me to perform a formatted write (the '-dpdf' option) of a plot (or figure) to a file.
I need the single quotes because the path name to the location where I want to write the file contains spaces. (I'm working on a Linux box running Fedora 24 updated daily.)
If I compute the file name using the line above, then cut and paste it into the print statement, everything works exactly as I wish it to. I've tried using
k=1;
file_name = sprintf("\'/home/user/directory to use/file%3.3i.pdf\'",k);
print ("-dpdf", '/home/user/directory to use/file001.pdf');
But simply switching to a different form of print statement doesn't solve the problem,although now I get an error message:
GPL Ghostscript 9.16: **** Could not open the file '/home/user/directory to use/file001.pdf' .
**** Unable to open the initial device, quitting.
warning: broken pipe
if you use foo a b this is the same as foo ("a", "b"). In your case you called print ("-dpdf", "file_name")
k = 1;
file_name = sprintf ("/home/user/directory to use/file%3.3i.pdf", k);
print ("-dpdf", file_name);
Observe:
>> k=1;
>> file_name = sprintf ('/home/tasos/Desktop/a folder with spaces in it/this is file number %3.3i.pdf', k)
file_name = /home/tasos/Desktop/a folder with spaces in it/this is file number 001.pdf
>> plot (1 : 10);
>> print (gcf, file_name, '-dpdf')
Tadaaa!
So yeah, no single quotes needed. The reason single quotes work when you're "typing it by hand" is because you're literally creating the string on the spot with the single quotes.
Having said that, it's generally a good idea when generating absolute paths to use the fullfile command instead. Have a look at it.
Tasos Papastylianou #TasosPapastylianou provided great help. My problem is now solved.

Disable warnings from within an Octave .oct file

Is it possible to do this? In particular I want to toggle between warning ("off", "Octave:broadcast") and warning ("on", "Octave:broadcast"), i.e. set warning off at the beginning of the .oct file and then set warning on just before the .oct file returns its output. Of course I could do this in the terminal or in the calling script file, but I'd like to do it in the .oct file itself if possible.
There's two ways to do it in C++, very similar to the Octave language itself.
disable_warning (const std::string& id);
set_warning_state (const std::string &id, const std::string &state);
Actually, disable_warning is just wrapper around the second option set_warning_state (id, "off"). Take a look into the error.cc for more options related to this. I'm sure you can figure out yourself how to turn the warning back on at the end ;)

How to Implement Grep into CGI script Please?

I am having difficulty figuring out how to implement grep into my CGI script. Basically I will receive a value of eg. 1500 from a HTML page. The CGI script then runs and compares 1500 to a text file. When it finds 1500 it prints the entire line and displays it on the webpage. I would like some tips and pointers on how to do this please. I understand that this involves grep but I don't really know how to put it in.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *data;
long m,n;
printf("%s%c%c\n",
"Content-Type:text/html;charset=iso-8859-1",13,10);
printf("<TITLE>Webpage of Results</TITLE>\n");
printf("<H1>Temperatures</H1>\n");
data = getenv("QUERY_STRING");
The HTML passes the variable time=1500. I understand (correct me if I am wrong) that QUERY_STRING will contain 1500?
some very straightforward analog of the grep in C is strstr() function
For a URL of the form whatever?query-string, the enviroment variable QUERY_STRING contains the full query-string - in you case time=1500 or similar.
You need to remember that there may be more then one field/value getting passed, seperated by &. By using strtok() you can retrieve the parts of the query string one by one, strcmp() lets you compare them to other strings.
If you found the right token, you need to work with a file:
fopen() is used for opening a file
fgets() is used to retrieve a line
use strstr() to check if a line contains a certain substring
use fclose() to close the file when you're done