كتبت الكود التالي الذي سوف أستخدمه في مشروع آخر ففكرت أني أحطه هنا ..
هو عبارة عن برنامج من أجل ترتيب كود السي بحيث يضيف مسافات بادئة من أجل سهولة القرائة ..
مثلا إذا ملف ما يحتوي على الكود التالي :
while (chr = *buffer, chr)
{
if (chr == '"' && prechr != '')
bString = !bString;
if (!bString) {
if (chr == '/' && prechr == '/')
if (chr == 'a')
{
printf("hello");
return buffer - 1;
}
chr = 'a';
}
buffer++;
}فبعد تنفيذ البرنامج عليه فإنه يعطينا
while (chr = *buffer, chr)
{
if (chr == '"' && prechr != '')
bString = !bString;
if (!bString) {
if (chr == '/' && prechr == '/')
if (chr == 'a')
{
printf("hello");
return buffer - 1;
}
chr = 'a';
}
buffer++;
}البرنامج يستخدم مفهوم التعاودية وأسس بسيطة جدا من المترجمات ولم أعطي انتباه لل comment من نوع /* و */ لأنه يوجد ملف آخر من أجلها .. وبالمناسبة هذه الخاصية موجودة في محرر فجوال سي في القائمة Edit ثم Advanced ثم Format Selection .
وهذا هو الكود
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define TABSIZE 4
#define COLON 255
#define CASE 254
#define ID 253
class AutoIndent {
public:
AutoIndent(istream& is, ostream& os);
~AutoIndent();
// Run the class on the given streams
int Run();
protected:
void Indent(int nLevel); // Regular Indent
void SemiIndent(int nLevel); // Special Indent for incomplete lines
void MultiLineMacro(int nLevel);// Special multi-line macro indent
bool GetLine(); // Get the next line from the stream
void PushCurrent(int nLevel); // outputs the current buffer after indenting
// used in mini parsing
bool CheckInCompleteLine(); // returns true if the line is not complete
bool CheckMultilineMacro(); // returns true if the line defines a multiline macro
int CountNextLevel(); // counts the '{' and '}'
// useful for mini scanning
void OmitSpaces(int &i); // omit the spaces
bool GetChar(int &i, char& chr);// get the next character
int Tocken(int &i); // get the next tocken
// returns a pointer in buffer to a line comment '//'
static char* LookForLineComment(char *buffer);
private:
istream& is;
ostream& os;
char buffer[255]; // holds the line
int ebuff_length; // holds the effective length
bool bMacroOn; // true if we are in a macro section
};
///////////////////////////////////////////////////////////
// The main function
//
int main(int argc, char **argv)
{
if (argc < 3) {
cerr << "Parameters : infile outfile" << endl;
return 1;
}
ifstream ifs(argv[1]);
ofstream ofs(argv[2]);
if (!ifs.is_open() || !ofs.is_open()) {
cerr << "Error openning the input or output files" << endl;
return 2;
}
AutoIndent ai(ifs, ofs);
return ai.Run();
}
///////////////////////////////////////////////////////////
// The implemintation section
//
AutoIndent::AutoIndent(istream& ris, ostream& ros) : is(ris), os(ros)
{
ebuff_length = 0;
bMacroOn = false;
}
AutoIndent::~AutoIndent()
{
// do nothing
}
int AutoIndent::Run()
{
Indent(0);
return 0;
}
char* AutoIndent::LookForLineComment(char *buffer)
{
bool bString = false;
char chr, prechr = '