How to send strings/commands to stdin - vala

While testing programs it would be nice to be able to pump strings into stdin for processing (libvala-0.36 on VSCode 1.15.0-insider/Linux Mint 18.2). Below is just for illustration, but stdin.puts/stdin.flush doesn't seem to work. How can I pump keystrokes/strings into stdin?
private void test_func(){
...do stuff
stdin.puts("""{"event":"server.connected","params":{"version":"0.0.1","pid":0}}""");
...do stuff
stdin.puts("exit\r\n");
}
public static int main (string[] args) {
string line;
...do stuff
#if DEBUG
test_func();
#endif
while ((line = stdin.read_line ()) != null) {
line = line.strip ();
if (line.length > 0) {
if (line == "exit") break;
gJsonRPC.handle_request (line);
}
}
...do stuff
}
Update:
Have not found functionality similar to .Net "SendKeys" class in GLib, so temporarily settled on this method....
public static void SendKeys(string sKeys) {
//--------------------------------------------------------------
//OSS:Hack:SendKeys
//--------------------------------------------------------------
char[] _keys = sKeys.to_utf8();
for (int i = _keys.length; i >= 0; i--)
stdin.ungetc (_keys[i]);
//--------------------------------------------------------------
}
#Lasall suggested FileStream.open(¨/dev/stdin¨, ¨w¨), so I try that next.

GLib.stdin really is just a GLib.FileStream.
You can encapsulate your processing code in a function that takes a FileStream like this:
public void my_processing_func (FileStream stream) {
while ((line = stream.read_line ()) != null) {
line = line.strip ();
if (line.length > 0) {
if (line == "exit") break;
gJsonRPC.handle_request (line);
}
}
}
}
Then in your main you can conditionally use either your test data or stdin:
#ifdef DEBUG
var stream = test_func ();
#else
var stream = stdin;
#endif
my_processing_func (stream);
I probably wouldn't use DEBUG, but some more descriptive name like TEST_DATA, also it might be better to use proper unit testing and write a test program instead of #ifdefing your main program.

Related

reinit.pas translated to C++

I have semi-successfully translated reinit.pas to C++ to use it in my project. The part where int __fastcall LoadNewResourceModule(LCID locale); is called works fine, in fact I can even call it prior to Application->Initialize() and it will load the proper language at startup. However, the part that calls void __fastcall ReinitializeForms(void); does not work, and gives a runtime error:
Resource TControl not found
Here is the dirty version of .cpp, and .h, I've yet to clean it up and comment it properly, at this point the thing just has to work fully. Please help me sort this out.
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <SysInit.hpp>
#include <Vcl.Forms.hpp>
#pragma hdrstop
#include "reinit.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
class TAsInheritedReader : public TReader
{
public:
void __fastcall ReadPrefix(TFilerFlags &_flags, int &_aChildPos);
inline __fastcall TAsInheritedReader(TStream* Stream, int BufSize) : TReader(Stream, BufSize) {}
};
//---------------------------------------------------------------------------
void __fastcall TAsInheritedReader::ReadPrefix(TFilerFlags &_flags, int &_aChildPos)
{
TReader::ReadPrefix(_flags, _aChildPos);
_flags = _flags << ffInherited;
}
//---------------------------------------------------------------------------
int __fastcall SetResourceHInstance(int _newInstance)
{
PLibModule CurModule = LibModuleList;
while(CurModule != NULL) {
if (reinterpret_cast<void*>(CurModule->Instance) == HInstance) {
if (CurModule->ResInstance != CurModule->Instance) {
FreeLibrary(reinterpret_cast<HMODULE>(CurModule->ResInstance));
CurModule->ResInstance = _newInstance;
return _newInstance;
}
CurModule = CurModule->Next;
}
}
return 0;
}
//---------------------------------------------------------------------------
int __fastcall LoadNewResourceModule(LCID locale)
{
wchar_t FileName[260];
PChar P;
wchar_t LocaleName[4];
int NewInst = 0;
GetModuleFileName(HInstance, FileName, sizeof(FileName));
GetLocaleInfo(locale, LOCALE_SABBREVLANGNAME, LocaleName, sizeof(LocaleName));
P = PChar(&FileName) + lstrlen(FileName);
while((*P != L'.') && (P != reinterpret_cast<PChar>(&FileName))) {
--P;
}
if (P != reinterpret_cast<PChar>(&FileName)) {
++P;
if (LocaleName[0] != L'\0') {
NewInst = reinterpret_cast<int>(LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE));
if (NewInst == 0) {
LocaleName[2] = L'\0';
lstrcpy(P, LocaleName);
NewInst = reinterpret_cast<int>(LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE));
}
}
}
if (NewInst != 0) {
return SetResourceHInstance(NewInst);
}
return 0;
}
//---------------------------------------------------------------------------
bool __fastcall InternalReloadComponentRes(const String ResName, THandle HInst, TComponent* Instance)
{
//TResourceStream* ResStream = new TResourceStream;
//TAsInheritedReader* AsInheritedReader = new TAsInheritedReader;
if (HInst == 0) {
HInst = reinterpret_cast<THandle>(HInstance);
}
THandle HRsrc = reinterpret_cast<THandle>(FindResource((HMODULE)HInst, (LPCWSTR)ResName.w_str(), (LPCWSTR)RT_RCDATA));
if(HRsrc != 0) {
return false;
}
/* THIS IS THE OFFENDING LINE OF CODE THAT THROWS EXCEPTION
I checked HInst, it is not 0...
ResName = "TControl"
and it throws exception here for some reason
saying resource tcontrol not found
*/
TResourceStream* ResStream = new TResourceStream(HInst, ResName, RT_RCDATA);
try {
TAsInheritedReader* AsInheritedReader = new TAsInheritedReader(ResStream, 4096);
try {
Instance = AsInheritedReader->ReadRootComponent(Instance);
} __finally {
delete AsInheritedReader;
}
}
__finally {
delete ResStream;
}
return true;
}
//---------------------------------------------------------------------------
bool __fastcall InitComponent(TClass ClassType)
{
if ((ClassType->ClassName() == "TComponent") || (ClassType->ClassName() == "RootAncestor")) {
return false;
}
InitComponent(ClassType->ClassParent());
return InternalReloadComponentRes(ClassType->ClassName(), FindResourceHInstance(FindClassHInstance(ClassType)), (TComponent*)&ClassType);
}
//---------------------------------------------------------------------------
bool __fastcall ReloadInheritedComponent(TComponent* Instance)
{
return InitComponent(Instance->ClassType());
}
//---------------------------------------------------------------------------
void __fastcall ReinitializeForms(void)
{
for(int i=0; i<Screen->FormCount-1; i++) {
ReloadInheritedComponent(Screen->Forms[i]);
}
}
#ifndef _reinit_h
#define _reinit_h
#include <windows.h>
extern int __fastcall LoadNewResourceModule(LCID locale);
extern void __fastcall ReinitializeForms(void);
#endif
You don't really need to translate the code at all. You can use Delphi .pas units as-is in C++Builder projects. Simply add the .pas file to your project and compile it, the IDE will generate a .hpp file that you can then #include in your C++ code.
In any case, your translation is not correct in many places.
For instance, the original code wasn't written with Unicode in mind, but you are using Unicode strings in your code. Expressions like sizeof(FileName) and sizeof(LocaleName) are the wrong buffer sizes to pass to the Win32 APIs being used, which can potentially allow buffer overflows. The code was clearly expecting BYTE-sized narrow characters, not WORD-sized wide characters.
It also looks like the original code was not written with 64-bit in mind, either. It is using 32-bit integers in places where 64-bit integers would be needed (for resource handles, etc).
So, the original code needs some updating to support modern systems properly.
But also, your translation of InitComponent() is wrong. It is using strings where the original code is using metaclass references instead, and it is passing the wrong value in the last parameter of InternalReloadComponentRes(), which you have not even declared correctly.
And also, your loop in ReinitializeForms() is skipping the last TForm in the Screen->Forms[] array.
Now, that all being said, try something more like this:
ReInit.h
#ifndef REINIT_H
#define REINIT_H
void __fastcall ReinitializeForms();
NativeUInt __fastcall LoadNewResourceModule(unsigned long Locale);
#endif
ReInit.cpp
#include "ReInit.h"
#include <Windows.hpp>
#include <SysInit.hpp>
#include <SysUtils.hpp>
#include <Classes.hpp>
#include <Forms.hpp>
#include <memory>
class TAsInheritedReader : public TReader
{
public:
void __fastcall ReadPrefix(TFilerFlags &Flags, int &AChildPos) override;
};
void __fastcall TAsInheritedReader::ReadPrefix(TFilerFlags &Flags, int &AChildPos)
{
TReader::ReadPrefix(Flags, AChildPos);
Flags << ffInherited;
}
NativeUInt __fastcall SetResourceHInstance(NativeUInt NewInstance)
{
PLibModule CurModule = LibModuleList;
while (CurModule)
{
if (CurModule->Instance == HInstance)
{
if (CurModule->ResInstance != CurModule->Instance)
::FreeLibrary(reinterpret_cast<HMODULE>(CurModule->ResInstance));
CurModule->ResInstance = NewInstance;
return NewInstance;
}
CurModule = CurModule->Next;
}
return 0;
}
NativeUInt __fastcall LoadNewResourceModule(unsigned long Locale)
{
WCHAR FileName[MAX_PATH+1] = {};
::GetModuleFileNameW(reinterpret_cast<HMODULE>(HInstance), FileName, MAX_PATH+1);
WCHAR LocaleName[5] = {};
::GetLocaleInfoW(Locale, LOCALE_SABBREVLANGNAME, LocaleName, 5);
LPWSTR P = &FileName[lstrlenW(FileName)];
while ((*P != L'.') && (P != FileName)) --P;
HMODULE NewInst = nullptr;
if (P != FileName)
{
++P;
if (LocaleName[0] != L'\0')
{
// Then look for a potential language/country translation
lstrcpyW(P, LocaleName);
NewInst = LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE);
if (!NewInst)
{
// Finally look for a language only translation
LocaleName[2] = L'\0';
lstrcpyW(P, LocaleName);
NewInst = LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE);
}
}
}
if (NewInst)
return SetResourceHInstance(reinterpret_cast<NativeUInt>(NewInst));
return 0;
}
bool __fastcall InternalReloadComponentRes(const UnicodeString &ResName, NativeUInt HInst, TComponent* &Instance)
{
// avoid possible EResNotFound exception
if (HInst == 0) HInst = HInstance;
HRSRC HRsrc = FindResourceW(reinterpret_cast<HMODULE>(HInst), ResName.c_str(), MAKEINTRESOURCEW(10)/*RT_RCDATA*/);
if (!HRsrc) return false;
auto ResStream = std::make_unique<TResourceStream>(HInst, ResName, MAKEINTRESOURCEW(10)/*RT_RCDATA*/);
auto AsInheritedReader = std::make_unique<TAsInheritedReader>(ResStream.get(), 4096);
Instance = AsInheritedReader->ReadRootComponent(Instance);
return true;
}
bool __fastcall ReloadInheritedComponent(TComponent *Instance, TClass RootAncestor)
{
const auto InitComponent = [&Instance,RootAncestor](TClass ClassType) -> bool
{
auto InitComponent_impl = [&Instance,RootAncestor](TClass ClassType, auto& InitComponent_ref) -> bool
{
if ((ClassType == __classid(TComponent)) || (ClassType == RootAncestor)) return false;
bool Result = InitComponent_ref(ClassType->ClassParent(), InitComponent_ref);
return InternalReloadComponentRes(ClassType->ClassName(), FindResourceHInstance(FindClassHInstance(ClassType)), Instance) || Result;
}
return InitComponent_impl(ClassType, InitComponent_impl);
}
return InitComponent(Instance->ClassType());
}
void __fastcall ReinitializeForms()
{
int Count = Screen->FormCount;
for(int i = 0; i < Count; ++i)
{
ReloadInheritedComponent(Screen->Forms[I], __classid(TForm));
}
}

Glib - interrupt foreach

I have very long collection - GList (huge amount of samples). For validation of every sample I am using g_list_foreach. The processing of the whole list lasts long. Sometimes it would be very useful to interrupt processing (via system signal SIGINT). Is there any way to interrupt foreach function?
It's trivial to implement something like g_list_foreach which would check a flag on each iteration, then you just need to install a signal handler to set the flag.
Here is the entire implementation of g_list_foreach:
void
g_list_foreach (GList *list,
GFunc func,
gpointer user_data)
{
while (list)
{
GList *next = list->next;
(*func) (list->data, user_data);
list = next;
}
}
How to install the handler will depend on how you want to structure your application, but if nothing else you could use a GOnce to install the handler, so something like:
static volatile gboolean my_flag = FALSE;
static void
handle_sigint(int id) {
my_flag = TRUE;
}
static gpointer
install_handler(gpointer data)
{
signal(SIGINT, handle_sigint);
return NULL;
}
/* Returns FALSE if interrupted, TRUE otherwise. */
gboolean
my_g_list_foreach (GList *list,
GFunc func,
gpointer user_data)
{
static GOnce handler_once = G_ONCE_INIT;
g_once(&handler_once, install_handler, NULL);
my_flag = FALSE;
while (list)
{
if (flag)
return FALSE;
GList *next = list->next;
(*func) (list->data, user_data);
list = next;
}
return TRUE;
}

How to combine traditional and Future-based API in one interface in Dart?

I would like to parse binary file (from some old game) as on desktop as in browser.
So, I should use abstract class, which can read binary data from array of bytes:
abstract class BinData {
int readByte();
String readNullString(){
var buffer = new StringBuffer();
int char;
do {
char = readByte();
if (char == 0){
break;
}
buffer.writeCharCode(char);
} while(true);
return buffer.toString();
}
}
Now I can implement my parser. For example:
class Parser {
BinData _data;
void load(BinData data){
...
}
}
For desktop console application I use dart:io RandomAccessFile:
class FileBinData extends BinData {
RandomAccessFile _file;
FileBinData.from(RandomAccessFile file){
this._file = file;
}
int readByte(){
return this._file.readByteSync();
}
}
For web application I have to use dart:html FileReader. However, this class has only Future-based API, which isn't compatible with my interface:
class WebFileBinData extends BinData {
File _file;
int _position = 0;
WebFileBinData.from(File file){
this._file = file;
}
int readByte(){
Blob blob = _file.slice(_position, _position + 1);
FileReader reader = new FileReader();
var future = reader.onLoad.map((e)=>reader.result).first
.then((e) { ... });
reader.readAsArrayBuffer(blob);
...
}
}
How can I solve it?
Your readByte() should return Future<int> instead of int. You can return a Future from a function/method even when it doesn't do any async operation (return new Future.value(5);) but you can not return int (or any non-Future value) from a function which executes async operations, at least not when the value should be returned as result of the async operation.
You also need to ensure to connect all async calls.
Future<int> readByte(){
return reader.onLoad.map((e)=>reader.result).first
.then((e) {
...
return reader.readAsArrayBuffer(blob);
});
** readNullString
Future<String> readNullString() {
var buffer = new StringBuffer();
int char;
return Future.doWhile(() {
return readByte().then((char) {
if (char == 0) {
return false; // end doWhile
}
buffer.writeCharCode(char);
return true; // continue doWhile
});
}).then((_) => buffer.toString()); // return function result
}

Error while downloading & saving image to sd card in blackberry?

I am working on blackberry project where i want to download image & save it in sd card in blackberry. By going through many sites i got some code & based on that i wrote the program but when it is executed the output screen is displaying a blank page with out any response. The code i am following is..
code:
public class BitmapDemo extends UiApplication
{
public static void main(String[] args)
{
BitmapDemo app = new BitmapDemo();
app.enterEventDispatcher();
}
public BitmapDemo()
{
pushScreen(new BitmapDemoScreen());
}
static class BitmapDemoScreen extends MainScreen
{
private static final String LABEL_X = " x ";
BitmapDemoScreen()
{
//BitmapField bmpFld1=new BitmapField(connectServerForImage("http://images03.olx.in/ui/3/20/99/45761199_1.jpg"));
//add(bmpFld1);
setTitle("Bitmap Demo");
// method for saving image in sd card
copyFile();
// Add a menu item to display an animation in a popup screen
MenuItem showAnimation = new MenuItem(new StringProvider("Show Animation"), 0x230010, 0);
showAnimation.setCommand(new Command(new CommandHandler()
{
public void execute(ReadOnlyCommandMetadata metadata, Object context)
{
// Create an EncodedImage object to contain an animated
// gif resource.
EncodedImage encodedImage = EncodedImage.getEncodedImageResource("animation.gif");
// Create a BitmapField to contain the animation
BitmapField bitmapFieldAnimation = new BitmapField();
bitmapFieldAnimation.setImage(encodedImage);
// Push a popup screen containing the BitmapField onto the
// display stack.
UiApplication.getUiApplication().pushScreen(new BitmapDemoPopup(bitmapFieldAnimation));
}
}));
addMenuItem(showAnimation);
}
private static class BitmapDemoPopup extends PopupScreen
{
public BitmapDemoPopup(BitmapField bitmapField)
{
super(new VerticalFieldManager());
add(bitmapField);
}
protected boolean keyChar(char c, int status, int time)
{
if(c == Characters.ESCAPE)
{
close();
}
return super.keyChar(c, status, time);
}
}
}
public static Bitmap connectServerForImage(String url) {
System.out.println("image url is:"+url);
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
int rc;
Bitmap bitmp = null;
try {
httpConnection = (HttpConnection) Connector.open(url,Connector.READ_WRITE);
rc = httpConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
httpInput = httpConnection.openInputStream();
InputStream inp = httpInput;
byte[] b = IOUtilities.streamToBytes(inp);
EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
return hai.getBitmap();
} catch (Exception ex) {
System.out.println("URL Bitmap Error........" + ex.getMessage());
} finally {
try {
if (httpInput != null)
httpInput.close();
if (httpDataOutput != null)
httpDataOutput.close();
if (httpConnection != null)
httpConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return bitmp;
}
public static void copyFile() {
// TODO Auto-generated method stub
EncodedImage encImage = EncodedImage.getEncodedImageResource("rim.png");
byte[] image = encImage.getData();
try {
// Create folder if not already created
FileConnection fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/images/");
if (!fc.exists())
fc.mkdir();
fc.close();
// Create file
fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/images/" + image, Connector.READ_WRITE);
if (!fc.exists())
fc.create();
OutputStream outStream = fc.openOutputStream();
outStream.write(image);
outStream.close();
fc.close();
System.out.println("image saved.....");
} catch (Exception e) {
// TODO: handle exception
//System.out.println("exception is "+ e);
}
}
}
This is the code which i am using. Not getting any response except blank page.. As i am new to blackberry development unable to find out what is the problem with my code. Can anyone please help me with this...... Actually i am having other doubt as like android & iphone does in blackberry simulator supports for SD card otherwise we need to add any SD card slots for this externally...
Waiting for your reply.....
To simply download and save that image to the SDCard, you can use this code. I changed your SDCard path to use the pictures folder, which I think is the standard location on BlackBerrys. If you really want to store it in images, you may just need to create the folder if it doesn't already exist.
package com.mycompany;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;
public class DownloadHelper implements Runnable {
private String _url;
public DownloadHelper(String url) {
_url = url;
}
public void run() {
HttpConnection connection = null;
OutputStream output = null;
InputStream input = null;
try {
// Open a HTTP connection to the webserver
connection = (HttpConnection) Connector.open(_url);
// Getting the response code will open the connection, send the request,
// and read the HTTP response headers. The headers are stored until requested.
if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
input = new DataInputStream(connection.openInputStream());
int len = (int) connection.getLength(); // Get the content length
if (len > 0) {
// Save the download as a local file, named the same as in the URL
String filename = _url.substring(_url.lastIndexOf('/') + 1);
FileConnection outputFile = (FileConnection) Connector.open("file:///SDCard/BlackBerry/pictures/" + filename,
Connector.READ_WRITE);
if (!outputFile.exists()) {
outputFile.create();
}
// This is probably not a robust check ...
if (len <= outputFile.availableSize()) {
output = outputFile.openDataOutputStream();
// We'll read and write this many bytes at a time until complete
int maxRead = 1024;
byte[] buffer = new byte[maxRead];
int bytesRead;
for (;;) {
bytesRead = input.read(buffer);
if (bytesRead <= 0) {
break;
}
output.write(buffer, 0, bytesRead);
}
output.close();
}
}
}
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
if (connection != null) {
connection.close();
}
if (input != null) {
input.close();
}
} catch (IOException e) {
// do nothing
}
}
}
}
This class can download an image in the background, as I suggested. To use it, you can start a worker thread like this:
DownloadHelper downloader = new DownloadHelper("http://images03.olx.in/ui/3/20/99/45761199_1.jpg");
Thread worker = new Thread(downloader);
worker.start();
This will save the file as /SDCard/BlackBerry/pictures/45761199_1.jpg. I tested it on a 5.0 Storm simulator.
There are several problems with the code posted. It's also not completely clear what you're trying to do. From the question title, I assume you want to download a jpg image from the internet, and display it.
1) You implement a method called connectServerForImage() to download an image, but then it's commented out. So, the method isn't going to download anything if it's not called.
2) Even if it's uncommented, connectServerForImage() is called here
BitmapField bmpFld1=new BitmapField(connectServerForImage("http://images03.olx.in/ui/3/20/99/45761199_1.jpg"));
This will block the main (UI) thread while it downloads your image. Even though you can do it this way, it's not a good thing to do. Instead, you could create a Thread to download the image as a background task, and then use UiApplication.invokeLater() to load the image into your BitmapField on the main/UI thread.
3) Your copyFile() method tries to copy a file named rim.png, which must be an image bundled with your application, and saves it to the SDCard. Is this really what you want? Do you want to save the downloaded image instead? This method doesn't seem to be connected to anything else. It's not saving the image downloaded from the internet, and the image it does save is never used anywhere else.
4) In copyFile(), this line
fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/images/" + image, Connector.READ_WRITE);
is passing a byte[] in as part of the filename to open (your variable named image). You should probably be adding a String name to the end of your SDCard path. As the code is, it's probably opening a file in the /SDCard/BlackBerry/images/ folder with a very long name that looks like a number. Or it might fail entirely, if there are limits on the length of filenames.
5) In Java, it's not usually a good idea to make everything static. Static should normally be used for constants, and for a very few methods like the main() method, which must be static.
Try to clean these things up, and then repost the code, and we can try to help you with your problem. Thanks.

Using streamreader to read line containing this "//"?

Read a Text file having any line starts from "//" omit this line and moved to next line.
The Input text file having some seprate partitions. Find line by line process and this mark.
If you are using .Net 3.5 you can use LINQ with a IEnumerable wrapped around a Stream Reader. This cool part if then you can just use a where statement to file statmens or better yet use a select with a regular expression to just trim the comment and leave data on the same line.
//.Net 3.5
static class Program
{
static void Main(string[] args)
{
var clean = from line in args[0].ReadAsLines()
let trimmed = line.Trim()
where !trimmed.StartsWith("//")
select line;
}
static IEnumerable<string> ReadAsLines(this string filename)
{
using (var reader = new StreamReader(filename))
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
...
//.Net 2.0
static class Program
{
static void Main(string[] args)
{
var clean = FilteredLines(args[0]);
}
static IEnumerable<string> FilteredLines(string filename)
{
foreach (var line in ReadAsLines(filename))
if (line.TrimStart().StartsWith("//"))
yield return line;
}
static IEnumerable<string> ReadAsLines(string filename)
{
using (var reader = new StreamReader(filename))
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
I'm not sure what you exactly need but, if you just want to filter out // lines from some text in a stream... just remember to close the stream after using it.
public string FilterComments(System.IO.Stream stream)
{
var data = new System.Text.StringBuilder();
using (var reader = new System.IO.StreamReader(stream))
{
var line = string.Empty;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
if (!line.TrimStart(' ').StartsWith("//"))
{
data.Append(line);
}
}
}
return data.ToString();
}
Class SplLineIgnorStrmReader:StreamReader // derived class from StreamReader
SplLineIgnorStrmReader ConverterDefFileReadStream = null;
{
//created the Obj for this Class.
Obj = new SplLineIgnorStrmReader(strFile, Encoding.default);
}
public override string ReadLine()
{
string strLineText = "", strTemp;
while (!EndOfStream)
{
strLineText = base.ReadLine();
strLineText = strLineText.TrimStart(' ');
strLineText = strLineText.TrimEnd(' ');
strTemp = strLineText.Substring(0, 2);
if (strTemp == "//")
continue;
break;
}
return strLineText;
This is if u want to read the Text file and omit any comments from that file(here exclude "//" comment).

Resources